C# 单击按钮时在gridview中添加新行

C# 单击按钮时在gridview中添加新行,c#,asp.net,C#,Asp.net,这是我的程序,页面加载gridview并将数据库记录检索到textbox,我放置了一个add new按钮,希望添加与该行完全相同的新行,但textbox是空的 我想在GridView中创建一个新行,同时在我的TextBox正在从数据库检索数据时单击addnew按钮。我试着运行代码,但当我点击按钮时什么也没发生。希望有人能帮忙。谢谢 我的前端代码 <Columns> <asp:TemplateField HeaderStyle-CssClass="displa

这是我的程序,页面加载gridview并将数据库记录检索到textbox,我放置了一个add new按钮,希望添加与该行完全相同的新行,但textbox是空的

我想在
GridView
中创建一个新行,同时在我的
TextBox
正在从数据库检索数据时单击addnew按钮。我试着运行代码,但当我点击按钮时什么也没发生。希望有人能帮忙。谢谢

我的前端代码

<Columns>
    <asp:TemplateField HeaderStyle-CssClass="display_none">
        <ItemTemplate>
            <asp:Label ID="Label3" runat="server" Font-Bold="true" Font-Size="Medium">Name</asp:Label>
        </ItemTemplate>
    </asp:TemplateField>

    <asp:TemplateField HeaderStyle-CssClass="display_none">

        <ItemTemplate>
            <asp:TextBox ID="TextBox1" runat="server" CssClass="NormalInputTextField" Text='<%#Eval("SLMN") %>'></asp:TextBox>
        </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderStyle-CssClass="display_none">
    <ItemTemplate>
         <asp:Button ID="BtnDelete" runat="server" Text="Delete" CssClass="btn btn-primary" CommandName="remove" CommandArgument='<%# Container.DataItemIndex %>'/>
    </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField FooterStyle-BorderStyle="None" HeaderStyle-CssClass="display_none">
    <ItemTemplate>
         <asp:Button ID="BtnSearch2" runat="server" Text="Search" CssClass="btn btn-primary"  CommandName="ViewComments" OnClientClick="javascript:saveData(this,'grid')"/>
    </ItemTemplate>
    <FooterStyle HorizontalAlign="Right" BorderStyle="None"/>
    <FooterTemplate>
         <asp:Button ID="BtnAdd" runat="server" Text="Add New Row" CssClass="btn btn-primary" OnClick="ButtonAdd_Click"/>
    </FooterTemplate>
    </asp:TemplateField>
</Columns>
我的onclick事件调用addnew函数

protected void ButtonAdd_Click(object sender, EventArgs e)
{
    AddNewRowToGrid();
}
我的gridview标签

<grd:MultiSelectGridView ID="grid2" runat="server" Width="500px" 
                        CssClass="paging_gridview" AllowPaging="True" 
                        AutoGenerateColumns ="false" PageSize="10" PagerType="Custom"  
                        ShowFooter="true" OnRowDeleting="grid2_RowDeleting" 
                        MultiSelectDataKeyName="Urid,Name" ShowHeaderWhenEmpty="true"
                        MultiSelectColumnIndex="0" EnableMultiSelect="false" GridLines="None" BorderStyle="None" OnRowCommand="grid2_RowCommand"
                        >

下面的教程详细介绍了完全相同的场景。请参考它。


下面的教程详细介绍了完全相同的场景。请参考它。


从LoadGrid方法中,您应该将数据作为数据表检索并绑定到网格。并保存在会话中。像这样:

private void Loadgrid()
        {

            var dt = new DataTable();

            using (var conn = new SqlConnection (ConfigurationManager.ConnectionStrings["ConnectionStringName"].ToString()))
            {

                var command = new SqlCommand();
                command.Connection = conn;
                command.CommandText = "SELECT * FROM [dbo].[T1]";
                command.CommandType = CommandType.Text;
                using (var adaptor = new SqlDataAdapter(command))
                {
                    if (conn.State == ConnectionState.Closed) conn.Open();
                    adaptor.Fill(dt);
                    if (conn.State == ConnectionState.Open) conn.Close();
                }

            }

                Session["ss"] = dt;
                grid2.DataSource = dt;
                grid2.DataBind();

            }


private void AddNewRowToGrid()
        {
            DataTable dt = (DataTable) Session["ss"];
            DataRow dr = null;
            DataRow newBlankRow1 = dt.NewRow();
            dt.Rows.Add(newBlankRow1);
            grid2.DataSource = dt;
            grid2.DataBind();

            Session["ss"] = dt;
        }

添加空行后,您还需要再次将数据绑定到网格。

从加载网格方法中,您应该将数据作为数据表检索并绑定到网格。并保存在会话中。像这样:

private void Loadgrid()
        {

            var dt = new DataTable();

            using (var conn = new SqlConnection (ConfigurationManager.ConnectionStrings["ConnectionStringName"].ToString()))
            {

                var command = new SqlCommand();
                command.Connection = conn;
                command.CommandText = "SELECT * FROM [dbo].[T1]";
                command.CommandType = CommandType.Text;
                using (var adaptor = new SqlDataAdapter(command))
                {
                    if (conn.State == ConnectionState.Closed) conn.Open();
                    adaptor.Fill(dt);
                    if (conn.State == ConnectionState.Open) conn.Close();
                }

            }

                Session["ss"] = dt;
                grid2.DataSource = dt;
                grid2.DataBind();

            }


private void AddNewRowToGrid()
        {
            DataTable dt = (DataTable) Session["ss"];
            DataRow dr = null;
            DataRow newBlankRow1 = dt.NewRow();
            dt.Rows.Add(newBlankRow1);
            grid2.DataSource = dt;
            grid2.DataBind();

            Session["ss"] = dt;
        }

添加空行后,还需要再次将数据绑定到网格。

创建一个新的数据表,添加一个空的
DataRow
,然后对该表不做任何操作。您真的希望此代码向现有数据源添加新行吗?正确的方法是从数据库加载
数据源
,因为它可能同时被更改。然后您可以轻松地添加另一行。之后,您将其作为数据源分配给GridView并调用
DataBind
。我还没有查看您的代码墙,但您正在实例化一个新的
DataTable
实例,而不是获取一个现有实例,这一事实看起来很可疑。我看不到DataTable和GridView之间的连接/绑定。获取您的DataTable,通过它,您可以绑定gridview,然后将新创建的行添加到旧数据表中,然后重新绑定gridview。@TimSchmelter嗨,我不知道怎么做。。。我希望新行与文本框中包含数据库记录的现有行相同,但前提是新行文本框为空。创建一个新数据表,添加一个空的
DataRow
,然后对该表不做任何操作。您真的希望此代码向现有数据源添加新行吗?正确的方法是从数据库加载
数据源
,因为它可能同时被更改。然后您可以轻松地添加另一行。之后,您将其作为数据源分配给GridView并调用
DataBind
。我还没有查看您的代码墙,但您正在实例化一个新的
DataTable
实例,而不是获取一个现有实例,这一事实看起来很可疑。我看不到DataTable和GridView之间的连接/绑定。获取您的DataTable,通过它,您可以绑定gridview,然后将新创建的行添加到旧数据表中,然后重新绑定gridview。@TimSchmelter嗨,我不知道怎么做。。。我希望新行与文本框中包含数据库记录的现有行相同,但前提是新行文本框为空..DataTable dt=ToDataTable(res);-->res在当前上下文中不是内容…DataTable dt=ToDataTable(res);-->res在当前上下文中不是内容。。。
private void AddNewRowToGrid()
    {
        int rowIndex = 0;

        if (ViewState["CurrentTable"] != null)
        {
            DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
            DataRow drCurrentRow = null;
            if (dtCurrentTable.Rows.Count > 0)
            {
                for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
                {
                    //extract the TextBox values
                    TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("TextBox1");
                    TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("TextBox2");
                    TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox3");
 //Instead of all the textboxes, use the button as you require.
                    drCurrentRow = dtCurrentTable.NewRow();
                    drCurrentRow["RowNumber"] = i + 1;

                    dtCurrentTable.Rows[i - 1]["Column1"] = box1.Text;
                    dtCurrentTable.Rows[i - 1]["Column2"] = box2.Text;
                    dtCurrentTable.Rows[i - 1]["Column3"] = box3.Text;

                    rowIndex++;
                }
                dtCurrentTable.Rows.Add(drCurrentRow);
                ViewState["CurrentTable"] = dtCurrentTable;

                Gridview1.DataSource = dtCurrentTable;
                Gridview1.DataBind();
            }
        }
        else
        {
            Response.Write("ViewState is null");
        }

        //Set Previous Data on Postbacks
        SetPreviousData();
    }
private void SetPreviousData()
    {
        int rowIndex = 0;
        if (ViewState["CurrentTable"] != null)
        {
            DataTable dt = (DataTable)ViewState["CurrentTable"];
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("TextBox1");
                    TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("TextBox2");
                    TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox3");

                    box1.Text = dt.Rows[i]["Column1"].ToString();
                    box2.Text = dt.Rows[i]["Column2"].ToString();
                    box3.Text = dt.Rows[i]["Column3"].ToString();

                    rowIndex++;
                }
            }
        }
    }
protected void ButtonAdd_Click(object sender, EventArgs e)
  {
        AddNewRowToGrid();
  }
private void Loadgrid()
        {

            var dt = new DataTable();

            using (var conn = new SqlConnection (ConfigurationManager.ConnectionStrings["ConnectionStringName"].ToString()))
            {

                var command = new SqlCommand();
                command.Connection = conn;
                command.CommandText = "SELECT * FROM [dbo].[T1]";
                command.CommandType = CommandType.Text;
                using (var adaptor = new SqlDataAdapter(command))
                {
                    if (conn.State == ConnectionState.Closed) conn.Open();
                    adaptor.Fill(dt);
                    if (conn.State == ConnectionState.Open) conn.Close();
                }

            }

                Session["ss"] = dt;
                grid2.DataSource = dt;
                grid2.DataBind();

            }


private void AddNewRowToGrid()
        {
            DataTable dt = (DataTable) Session["ss"];
            DataRow dr = null;
            DataRow newBlankRow1 = dt.NewRow();
            dt.Rows.Add(newBlankRow1);
            grid2.DataSource = dt;
            grid2.DataBind();

            Session["ss"] = dt;
        }