How to programmatically insert a row in a GridView?

我是研究僧i 提交于 2019-12-03 19:11:00

问题


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!


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/181158/how-to-programmatically-insert-a-row-in-a-gridview

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