Bind ASPxGridView to a DataTable
- 2 minutes to read
Follow the steps below to bind the ASPxGridView control to a DataTable created at runtime:
Add ASPxGridView to the form.
Specify the KeyFieldName property. Key field values should be unique.
Create a DataTable (see the GetTable function) and assign it to the ASPxGridView.DataSource property.
Handle the Page_Init event to bind the grid to the data table. Call the ASPxGridView.DataBind method to bind the grid to data on every request to the server.
The ASPxGridView control does not store its bound data in the ViewState (EnableViewState) between requests. You should supply data to the control on every page request.
We also recommend that you disable the EnableViewState property if you create the ASPxGridView control dynamically.
<dx:ASPxGridView runat="server" ID="ASPxGridView1" KeyFieldName="id" EnableRowsCache="false" ... > ... </dx:ASPxGridView>
protected void Page_Init(object sender, EventArgs e) { ASPxGridView1.DataSource = GetTable(); ASPxGridView1.DataBind(); AddColumns(GetTable()); } private void AddColumns(DataTable table) { ASPxGridView1.Columns.Clear(); foreach (DataColumn c in table.Columns) { GridViewDataTextColumn column = new GridViewDataTextColumn(); column.FieldName = c.ColumnName; ASPxGridView1.Columns.Add(column); } } DataTable GetTable() { DataTable 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()); return table; }
The ASPxGridView caches data to remain fast and responsive. See the following articles for more information on how the row cache works:
[KB Article] ASPxGridView Row Cache
[Online Example] Bind the ASPxGridView to a DataTable in code