How to programmatically insert a row in a GridView?

前端 未结 2 945
说谎
说谎 2020-12-29 16:07

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

相关标签:
2条回答
  • 2020-12-29 16:36

    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

    0 讨论(0)
  • 2020-12-29 16:42

    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;
    }
    
    0 讨论(0)
提交回复
热议问题