2009/05/20

DataGrid.DataSource return null?

There will be a time that you want to get the bound datagrid's datasource to work on it. For example: you want to have a button that can add in new row dynamically to the bound datagrid. But when you try to do this: DataTable dt = (DataTable)dg.DataSource, you will then realize that dt returns null.

Solution:
Actually .NET 2.0 would not save the datasource when the datagrid is bound. What you can do is to save the datasource into a view state variable. For example:

When you bind a datagrid, you also need to set viewstate varible to the same source:

dg.DataSource = ds;
ViewState["temp"] = ds;
dg.DataBind();

So, when you want to retrieve the datasource, you can do this:
DataTable dt = (DataTable)ViewState["temp"];

If you want to add a new row, you can do this:
DataTable dt = (DataTable)ViewState["temp"];
DataRow dr = dt.NewRow();
dt.Rows.Add(dr);
ViewState["temp"] = dt;
dg.DataSource = dt;
dg.DataBind();

Good Luck!

No comments:

Post a Comment