Category:
ASP.Net 2.0
I don’t know if all of you find the post ”Add a new row to the GridView control dynamically when a row is selected.” Interesting, but since I wrote it, there has been some changes so the code example in the post will not work. So I decide to mention some of the changes to make it work.
First of all there is a problem of using the DataBound event. If we use the DataBound event to add a new row to the GridView, it will not appear until the next time a postback is performed. Instead we now use the PreRender event.
<asp:GridView
ID="GridView1"
Runat="server"
DataSourceID="SqlDataSource1" DataKeyNames="CustomerID"
AutoGenerateColumns="False"
OnPreRender="GridView1_PreRender" ..>
The code in the “Add a new row ….” Post will case the SelectedRow’s Parent object into a ChildTable. This will not work anymore because the ChildTable is now protected, so instead we cast it to the ChildTable base class, which is the Table class. So the GridView1_PreRender method that is hooked up to the OnPreRender event now will look like the following code:
void GridView1_PreRender(object sender, EventArgs e)
{
if (GridView1.SelectedRow != null)
{
Table table = GridView1.SelectedRow.Parent as Table;
if (table != null)
CreateRow(table, GridView1.SelectedIndex);
}
}
The CreateRow method that is called inside the code above takes a ChildTable as an argument, the type of the argument most also be changed to the Type Table instead of ChildTable:
private void CreateRow(Table table, int index)
{
GridViewRow row = new GridViewRow(-1, -1, DataControlRowType.DataRow, DataControlRowState.Normal);
row.Cells.Add(CreateColumn());
table.Rows.AddAt(index + 2, row);
}
When the changes above is done, the code will work perfectly again.
|