GridView设计:如何在按钮单击后在GridView中添加空白新行

时间:2014-03-18 06:25:59

标签: c# asp.net gridview data-binding

我的GridView下面有一个Button。单击按钮后,我想在GridView下面添加一个新的空白行

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:Button ID="btnTest" Text="Test" runat="server" OnClick="btnTest_Click" />
        </div>

        <table border="0" cellpadding="0" cellspacing="0">
            <tr>
                <td>
                    <strong>Dynamic Grid</strong></td>
            </tr>
            <tr>
                <td>
                    <asp:GridView ID="GrdDynamic" runat="server" AutoGenerateColumns="true"
                         OnRowDataBound="GrdDynamic_RowDataBound" >
                    </asp:GridView>
  </td>
            </tr>
        </table>
        <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
    </form>
</body>
</html>

并且数据正在通过以下方式填充....

在pageLoad中我调用了绑定

 DataTable dt = GroupBudgetSetUpBLL.Instance.GetAllGroupBudgetSetUp();
            GrdDynamic.DataSource = dt;
            GrdDynamic.DataBind();

并且在rowdatabound中我正在制作网格可编辑文本框。

protected void GrdDynamic_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        for (int i = 1; i < e.Row.Cells.Count; i++)
        {
            TextBox txt = new TextBox();
            string budget = e.Row.Cells[i].Text.Split('_').LastOrDefault();
            string txtID = e.Row.Cells[i].Text.Split('_').FirstOrDefault() + "_" + e.Row.Cells[i].Text.Split('_').Skip(1).FirstOrDefault();
            txt.ID = txtID;
            txt.Text = budget;
            e.Row.Cells[i].Text = "";
            e.Row.Cells[i].Controls.Add(txt);
        }
    }
}

现在点击网格下面的“按钮”我想在MainGrid下面显示一个空白行,单元格控件类型将是TextBox,以便它仍然可以编辑。

1 个答案:

答案 0 :(得分:0)

我可以从你的问题中推断出你需要在GridView下面添加一个新的空行(看起来像button_click上的GridView的最后一行是空白的)。

我不确定将新行添加到数据绑定网格视图是多么可行,而是你可以做的是在数据表中添加一个空白行,如下所示:

将以下代码添加到button1_Click()

protected void Button1_Click(object sender, EventArgs e)
        {
            DataTable dt = GroupBudgetSetUpBLL.Instance.GetAllGroupBudgetSetUp();
            DataRow myRow = dt.NewRow();
            dt.Rows.InsertAt(myRow, dt.Rows.Count);
            GrdDynamic.DataSource = dt;
            GrdDynamic.DataBind();
        }