How to programmatically insert a row in a GridView?

↘锁芯ラ 提交于 2019-11-30 05:27:31

I think I figured it out. Here is a solution that seems to work. It could be improved using user controls but this is the gist of it:

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;
}

Thank you for sharing this code.

I am trying to do the same thing (creating nested gridview), but actually, you don't have to create the gridview yourself. Instead, you just can wrap the control within tags. I have seen an example here http://www.codeproject.com/KB/aspnet/EditNestedGridView.aspx?msg=3089755#xx3089755xx

You would see that the developer has nested gv control just by wraping the second gridview control within tags.

If you CAN do what he is doing by code, it would be more effecient. You wouldn't need to display all selected fields!! In addition, you would visually be able to have some controls added to your child gridview.

I have converted your code to vb and working perfectly.

Thanks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!