Skip to main content

How to: Bind the ASPxGridView to Data Created at Runtime (DataTable)

  • 2 minutes to read

This example demonstrates how you can programmatically create a DataTable and then bind a grid control to it.

The ASPxGridView control supports the caching mechanism. If you wish to use it and bind the grid at runtime, see the example below. In this case, ASPxGridView is repopulated only when it requires data. In other cases, the grid takes data from its own custom callback state.

See Also:

Bind Grid View to Data at Runtime

Built-in Row Cache

 

Refer to the following example for more information: Bind a grid to a DataTable via code.

protected void Page_Load(object sender, EventArgs e) {
     if (!IsPostBack && !IsCallback) {
          //Create columns on the first load.
          GridViewDataColumn id = new GridViewDataColumn();
          id.FieldName = "id";
          grid.Columns.Add(id);
          GridViewDataColumn data = new GridViewDataColumn();
          data.FieldName = "data";
          grid.Columns.Add(data);
     }
     //Bind the grid only once.
     if (!IsPostBack)
     grid.DataBind();
}

protected void grid_DataBinding(object sender, EventArgs e) {
     // Assign the data source in grid_DataBinding.
     grid.DataSource = GetTable();
}

DataTable GetTable() {
     //You can store a DataTable in the session state.
     DataTable table = Session["Table"] as DataTable;
     if (table == null) {
          table = new DataTable();
          table.Columns.Add("id", typeof(int));
          table.Columns.Add("data", typeof(String));
          for (int n = 0; n < 100; n++) {
              table.Rows.Add(n, "row" + n.ToString());
          }
          Session["Table"] = table;
     }
     return table;
}