Sunday, July 13, 2008

Create Rows Dynamically to a GridView

Many times we worried how to add rows dynamically to a GridView. This might be the case when we need to display the Master - Detail Information. For Example, There is a GridView populated with the Department data. Here our requirment is whenever we select a department from the GrdiView, automatically a new row need to be created exactly next to the selected row which contains another GridView populated with Employees data related to select Department. If this is the case first we need to create a new exactly next to the selected row. These are the steps to create a new row :

  1. Add a GridView to your aspx page.

  2. Populate with data using any datasource control (ObjectDataSource, SQLDataSource, etc.)


Then, your ccode may looks like:


< asp:GridView ID="departmentGridView" Runat="server" DataSourceID="DepartmentObjectDataSource" DataKeyNames="DeptID" AutoGenerateColumns="False" cellpadding="5" OnSelectedIndexChanged="departmentGridView_SelectedIndexChanged" >
     .......
     .......
     .......
</asp:GridView>

In the above code you find a event OnSelectedIndexChanged which fires when a row's Select button is clicked, but after the GridView control handles the select operation. Now, we use this onSelectedIndexChanged Event to create a new row exactly next to the selected row. Then the code for OnSelectedIndexChanged event may looks like :


protected void departmentGridView_SelectedIndexChanged(object sender, EventArgs e)
{
     if (departmentGridView.SelectedRow != null)
     {
          Table table = new Table();
          if (table != null)
                addNewRow(table, departmentGridView.SelectedIndex)
     }
}

private void addNewRow(Table table, int SelectedIndex)
{
     GridViewRow GridRow = new GridViewRow(-1, -1, DataControlRowType.DataRow, DataControlRowState.Normal);
     Row.Cells.Add(generateColumns());
     table.Rows.AddAt(SelectedIndex+ 2, GridRow);
}

private TableCell generateColumns()
{
     TableCell Cell1= new TableCell();
     Cell1.ColumnSpan = departmentGridView.Columns.Count;
     Cell1.style["width"] = "100%";
     /* Here you can create any control and add that control to this Cell */
     Button btn = new Button();
     btn.Text = "Click Me";
     Cell1.Controls.Add(btn);
     return Cell1;
}

In the above code instead of Button control you can create a GridView Control and add it to the TableCell. By this way we can dynamically add row to a GridView on demand.

1 comment:

Anonymous said...

Great man, Thanks I'm looking for this for a long time.