views:

6272

answers:

2

i have a databound GridView in asp.net 2.0 with a row-selection link. When a row is selected, I want to programmatically add a table row below the selected row, in order to nest another grid et al.

I am researching this for a client and for an article, and i think my google-fu is not strong tonight. Any suggestions?

EDIT: I actually had a working solution but Visual Studio was nutted up somehow; closing and re-opening VS and rebuilding everything fixed the problem ;-)

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

+2  A: 

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;
}
Steven A. Lowe
+1  A: 

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

Mrkhalid