Fredrik Normén's Blog - NSQUARED²
Any fool can write code that a computer can understand. Good programmers write code that humans can understand.

Microsoft Most Valuable Professional
     .Net Framework - ASP.Net - Architecture - Development
NOTE: This list of posts will only list the 15 latest posts, to see the rest, select from the Archives located in the menu to the left. The RSS will only list the 10 lastest posts.
Changes to make the code in the Add a new row ro the GridView ... post work.

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.

Posted: Wednesday, August 10, 2005 - 09:42 GMT+1    Print     E-mail    Comments (13)
   fredrik.nsquared2.com - 2007