C# 如何使用gridview中的按钮单击并在gridview中显示数据库中插入的行来添加空行并将该行插入数据库?

C# 如何使用gridview中的按钮单击并在gridview中显示数据库中插入的行来添加空行并将该行插入数据库?,c#,sql,asp.net,sql-server,gridview,C#,Sql,Asp.net,Sql Server,Gridview,这里显示的代码是添加一个空行并将该行插入数据库,但在运行时不显示该行。请有人可以编辑该代码,并帮助我得到我所期望的。请帮帮我。我受够了做这些事。我不明白。如果有人有我期望的代码,请发送给我的邮箱id:sivaraman。loganathan@gmail.com <body> <form id="form1" runat="server"> <div> <asp:gridview ID="Gridview1" runat="server" ShowFoot

这里显示的代码是添加一个空行并将该行插入数据库,但在运行时不显示该行。请有人可以编辑该代码,并帮助我得到我所期望的。请帮帮我。我受够了做这些事。我不明白。如果有人有我期望的代码,请发送给我的邮箱id:sivaraman。loganathan@gmail.com

<body>
<form id="form1" runat="server">
<div>
<asp:gridview ID="Gridview1" runat="server" ShowFooter="true"   AutoGenerateColumns="false">
    <Columns>
    <asp:BoundField DataField="RowNumber" HeaderText="Row Number" />
    <asp:TemplateField HeaderText="Header 1">
        <ItemTemplate>
            <asp:TextBox ID="TextBox1" runat="server" Text='<%# Eval("Column1") %>'></asp:TextBox>
        </ItemTemplate>
        <EditItemTemplate>
         <asp:TextBox ID="TextBox1" runat="server" ></asp:TextBox>
        </EditItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="Header 2">
        <ItemTemplate>
            <asp:TextBox ID="TextBox2" runat="server" Text='<%# Eval("Column2") %>'></asp:TextBox>
        </ItemTemplate>
        <EditItemTemplate>
         <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
        </EditItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="Header 3">
        <ItemTemplate>
             <asp:TextBox ID="TextBox3" runat="server" Text='<%# Eval("Column3") %>'></asp:TextBox>
        </ItemTemplate>
        <EditItemTemplate>
         <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
        </EditItemTemplate>
    </asp:TemplateField>
    </Columns>
</asp:gridview>
<asp:Button ID="ButtonAdd" runat="server" Text="Add New Row" 
            OnClick="ButtonAdd_Click" />
<asp:Button ID="Button1" runat="server" Text="Button" 
            OnClick="ButtonSave_Click"/>
</div>
</form>
</body>

代码隐藏:

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        SetInitialRow();
    }
}

private void BindData()
{
    DataTable dt = new DataTable();

    using (SqlConnection con = new SqlConnection(GetConnectionString()))
    {
        string strQuery = "SELECT * FROM SampleTabL";
        SqlCommand cmd = new SqlCommand(strQuery);

        using (SqlDataAdapter sda = new SqlDataAdapter())
        {
            cmd.Connection = con;
            con.Open();
            sda.SelectCommand = cmd;
            sda.Fill(dt);
            Gridview1.DataSource = dt;
            Gridview1.DataBind();
        }
    }
}

private void SetInitialRow()
{
    DataTable dt = new DataTable();
    DataRow dr = null;

    dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
    dt.Columns.Add(new DataColumn("Column1", typeof(string)));
    dt.Columns.Add(new DataColumn("Column2", typeof(string)));
    dt.Columns.Add(new DataColumn("Column3", typeof(string)));

    dr = dt.NewRow();
    dr["RowNumber"] = 1;
    dr["Column1"] = string.Empty;
    dr["Column2"] = string.Empty;
    dr["Column3"] = string.Empty;

    dt.Rows.Add(dr);
    //dr = dt.NewRow();

    //Store the DataTable in ViewState
    ViewState["CurrentTable"] = dt;

    Gridview1.DataSource = dt;
    Gridview1.DataBind();
}

protected void ButtonAdd_Click(object sender, EventArgs e)
{
    AddNewRowToGrid();
}

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");

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

private string GetConnectionString()
{
    //"DBConnection" is the name of the Connection String
    //that was set up from the web.config file
    return System.Configuration.ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
}

private void InsertRecords(StringCollection sc)
{
    SqlConnection conn = new SqlConnection(GetConnectionString());
    StringBuilder sb = new StringBuilder(string.Empty);
    string[] splitItems = null;

    foreach (string item in sc)
    {
        const string sqlStatement = "INSERT INTO SampleTabl (Column1,Column2,Column3) VALUES";

        if (item.Contains(","))
        {
            splitItems = item.Split(",".ToCharArray());
            sb.AppendFormat("{0}('{1}','{2}','{3}'); ", sqlStatement, splitItems[0], splitItems[1], splitItems[2]);
        }
    }

    try
    {
        conn.Open();
        SqlCommand cmd = new SqlCommand(sb.ToString(), conn);
        cmd.CommandType = CommandType.Text;
        cmd.ExecuteNonQuery();

        //Display a popup which indicates that the record was successfully inserted
        Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Script", "alert('Records Successfuly Saved!');", true);
    }
    catch (System.Data.SqlClient.SqlException ex)
    {
        string msg = "Insert Error:";
        msg += ex.Message;
        throw new Exception(msg);
    }
    finally
    {
        conn.Close();
    }
}

protected void ButtonSave_Click(object sender, EventArgs e)
{
    int rowIndex = 0;
    StringCollection sc = new StringCollection();

    if (ViewState["CurrentTable"] != null)
    {
        DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];

        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");

                //get the values from the TextBoxes
                //then add it to the collections with a comma "," as the delimited values
                sc.Add(box1.Text + "," + box2.Text + "," + box3.Text);
                rowIndex++;
            }

            //Call the method for executing inserts
            InsertRecords(sc);
        }
    }
}
受保护的无效页面加载(对象发送方,事件参数e)
{
如果(!Page.IsPostBack)
{
SetInitialRow();
}
}
私有void BindData()
{
DataTable dt=新的DataTable();
使用(SqlConnection con=newsqlconnection(GetConnectionString()))
{
string strQuery=“SELECT*FROM SampleTabL”;
SqlCommand cmd=新的SqlCommand(strQuery);
使用(SqlDataAdapter sda=newsqldataadapter())
{
cmd.Connection=con;
con.Open();
sda.SelectCommand=cmd;
sda.填充(dt);
Gridview1.DataSource=dt;
Gridview1.DataBind();
}
}
}
私有void SetInitialRow()
{
DataTable dt=新的DataTable();
数据行dr=null;
添加(新的数据列(“行数”,typeof(字符串));
Add(新的数据列(“Column1”,typeof(string));
Add(新的数据列(“Column2”,typeof(string));
Add(新的数据列(“Column3”,typeof(string));
dr=dt.NewRow();
dr[“行数”]=1;
dr[“Column1”]=string.Empty;
dr[“Column2”]=string.Empty;
dr[“Column3”]=string.Empty;
dt.Rows.Add(dr);
//dr=dt.NewRow();
//将数据表存储在ViewState中
视图状态[“当前表”]=dt;
Gridview1.DataSource=dt;
Gridview1.DataBind();
}
受保护的无效按钮单击(对象发送者,事件参数e)
{
AddNewRowToGrid();
}
私有void AddNewRowToGrid()
{
int rowIndex=0;
如果(ViewState[“CurrentTable”]!=null)
{
DataTable dtCurrentTable=(DataTable)视图状态[“CurrentTable”];
DataRow drCurrentRow=null;
如果(dtCurrentTable.Rows.Count>0)
{
对于(int i=1;i 0)
{
对于(int i=0;i0)
{

对于(int i=1;i问题不是很清楚,因此我假设您希望存储插入
gridview
中的数据,并希望在页面加载后将其显示在同一
gridview

如果是这种情况,那么代码的问题是,您没有在
pageload
上调用
BindData()方法
。另一个调用
SetInitialRow()
的方法在
pageload
上可能会弄乱您试图绑定数据的
gridview

您可以执行以下操作:

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {                
        BindData();                
    }
}

private void BindData()
{
    DataTable dt = new DataTable();

    using (SqlConnection con = new SqlConnection(GetConnectionString()))
    {
        string strQuery = "SELECT * FROM SampleTabL";
        SqlCommand cmd = new SqlCommand(strQuery);

        using (SqlDataAdapter sda = new SqlDataAdapter())
        {
            cmd.Connection = con;
            con.Open();
            sda.SelectCommand = cmd;
            sda.Fill(dt);
            if (dt.Rows.Count>0)
            {
                Gridview1.DataSource = dt;
                Gridview1.DataBind();
            }
            else
            {
                SetInitialRow();
            }
        }
    }
}

堆栈溢出不是一项代码编写服务。我们可以提供帮助,但我们不是来为您完成工作的。请帮助我完成此任务您创建了新行,但从未将其添加到表中。