Skip to main content

How to: Implement Data Editing When a Grid is Bound to a Table Created At Runtime

  • 3 minutes to read

In this example, the ASPxGridView is bound to a DataTable created at runtime. The data table is stored within a Session. To enable data management, handle the following events:

Note

You should specify the ASPxGridBase.KeyFieldName property to perform data edit operations.

The animation below shows the result:

RuntimeCreatedDataManagement

using System.Data;
...
protected void Page_Load(object sender, EventArgs e) {
    if (Session["GridData"] == null)
        Session["GridData"] = CreateData();

    ASPxGridView1.DataSource = Session["GridData"];

    if (!IsPostBack && !IsCallback)
        ASPxGridView1.DataBind();
}

private DataTable CreateData() {
    DataTable table = new DataTable();
    table.PrimaryKey = new DataColumn[] { table.Columns.Add("ID", typeof(Guid)) };
    table.Columns.Add("Person", typeof(string));
    table.Columns.Add("Age", typeof(int));
    table.Rows.Add(new object[] { Guid.NewGuid(), "Mike", 30 });
    table.Rows.Add(new object[] { Guid.NewGuid(), "Rosa", 22 });
    table.Rows.Add(new object[] { Guid.NewGuid(), "Nick", 18 });
    return table;
}
protected void ASPxGridView1_RowInserting(object sender,
    DevExpress.Web.Data.ASPxDataInsertingEventArgs e) {
    ((DataTable)Session["GridData"]).Rows.Add(new object[] { Guid.NewGuid(),
                            e.NewValues["Person"], e.NewValues["Age"] });
    e.Cancel = true;
    ASPxGridView1.CancelEdit();
    ASPxGridView1.DataBind();
}
protected void ASPxGridView1_RowUpdating(object sender, 
DevExpress.Web.Data.ASPxDataUpdatingEventArgs e) {
    DataRow row = ((DataTable)Session["GridData"]).Rows.Find(e.Keys["ID"]);
    row["Person"] = e.NewValues["Person"];
    row["Age"] = e.NewValues["Age"];
    e.Cancel = true;
    ASPxGridView1.CancelEdit();
    ASPxGridView1.DataBind();
}
protected void ASPxGridView1_RowDeleting(object sender, 
DevExpress.Web.Data.ASPxDataDeletingEventArgs e) {
    DataRow row = ((DataTable)Session["GridData"]).Rows.Find(e.Keys["ID"]);
    ((DataTable)Session["GridData"]).Rows.Remove(row);
    e.Cancel = true;
    ASPxGridView1.DataBind();
}