如何以编程方式在 GridView 中插入一行? [英] How to programmatically insert a row in a GridView?

查看:28
本文介绍了如何以编程方式在 GridView 中插入一行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 asp.net 2.0 中有一个带有行选择链接的数据绑定 GridView.选择一行时,我想以编程方式在所选行下方编程添加表行,以嵌套另一个Grid等.

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.

我正在为一个客户和一篇文章研究这个,我认为我的 google-fu 今晚不强.有什么建议吗?

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

我实际上有一个可行的解决方案,但 Visual Studio 不知何故被搞砸了;关闭并重新打开 VS 并重建一切解决了问题;-)

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!

推荐答案

我想我明白了.这是一个似乎有效的解决方案.可以使用用户控件改进它,但这是它的要点:

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

这篇关于如何以编程方式在 GridView 中插入一行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆