How to programmatically insert a row in a gridview?

I have a GridView binding in asp.net 2.0 with a row select link. When a row is selected, I want to programmatically add a table row below the selected row to insert another grid, etc.

I will research this for the client and for the article, and I think that my google-fu is not strong today. Any suggestions?

EDIT: I actually had a working solution, but Visual Studio somehow learned; closing and reopening VS and restoring all fixed problems; -)

My solution is published below, please tell me how to make it better, if possible. Thanks!

+5
gridview databound
source share
2 answers

I think I get it. Here is a solution that seems to work. It can be improved with custom controls, but this is its essence:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow && (e.Row.RowState & DataControlRowState.Selected) > 0) { Table tbl = (Table)e.Row.Parent; GridViewRow tr = new GridViewRow(e.Row.RowIndex + 1, -1, DataControlRowType.EmptyDataRow, DataControlRowState.Normal); TableCell tc = new TableCell(); tc.ColumnSpan = GridView1.Columns.Count; tc.Controls.Add( makeChildGrid(Convert.ToInt32( ((DataRowView)e.Row.DataItem)["ROW_ID_FIELD"]))); tr.Cells.Add(tc); tbl.Rows.Add(tr); } } protected GridView makeChildGrid(int id) { GridView gv = new GridView(); SqlDataSource sqlds = new SqlDataSource(); sqlds.DataSourceMode = SqlDataSourceMode.DataSet; sqlds.ConnectionString = SqlDataSource1.ConnectionString; sqlds.SelectCommand = "SELECT * from MY_TABLE_NAME " + "WHERE KEY_FIELD = " + id.ToString(); DataView dv = (DataView)sqlds.Select(DataSourceSelectArguments.Empty); gv.DataSource = dv; gv.DataBind(); //not sure this is necessary...? return gv; } 
+8
source share

Thanks for sharing this code.

I am trying to do the same (creating a nested gridview), but in fact you do not need to create a gridview yourself. Instead, you can simply wrap the control in tags. I gave an example here http://www.codeproject.com/KB/aspnet/EditNestedGridView.aspx?msg=3089755#xx3089755xx

You will see that the developer has nested gv control by simply crushing the second gridview control in the tags.

If you CAN do what it does by code, that would be more efficient. You will not need to display all selected fields! In addition, you could visually have some controls added to your child's gridview.

I converted your code to vb and it works fine.

thanks

+1
source share

All Articles