aspnet-3788-components-grid-view-examples-how-to-bind-the-aspxgridview-to-data-created-at-runtime-datatable.md
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
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;
}
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
If (Not IsPostBack) AndAlso (Not IsCallback) Then
'Create columns on the first load.
Dim id As New GridViewDataColumn()
id.FieldName = "id"
grid.Columns.Add(id)
Dim data As New GridViewDataColumn()
data.FieldName = "data"
grid.Columns.Add(data)
End If
'Bind the grid only once.
If (Not IsPostBack) Then
grid.DataBind()
End If
End Sub
Protected Sub grid_DataBinding(ByVal sender As Object, ByVal e As EventArgs)
' Assign the data source in grid_DataBinding.
grid.DataSource = GetTable()
End Sub
Private Function GetTable() As DataTable
'You can store a DataTable in the session state.
Dim table As DataTable = TryCast(Session("Table"), DataTable)
If table Is Nothing Then
table = New DataTable()
table.Columns.Add("id", GetType(Integer))
table.Columns.Add("data", GetType(String))
For n As Integer = 0 To 99
table.Rows.Add(n, "row" & n.ToString())
Next n
Session("Table") = table
End If
Return table
End Function
<dx:ASPxGridView ID="grid" ClientInstanceName="grid" runat="server" Width="300px"
AutoGenerateColumns="False" OnDataBinding="grid_DataBinding">
</dx:ASPxGridView>