【问题标题】:Data insert dynamically multiple rows one-button click数据动态插入多行一键点击
【发布时间】:2016-03-30 05:49:11
【问题描述】:

我想通过单击按钮一次插入数据,其中有一个下拉列表选择的数字和两个文本框。我选择下拉列表编号 [例如。 2]并在两个文本框中输入数据,然后单击一次插入按钮。数据保存在数据库表中多行,从下拉列表中选择多少个数字。例如:

下拉列表 = 0,1,2,3,4 ; // 选择任意数字在数据库表中插入多行

[1]文本框=“数据”; // 输入数据
[2]文本框=“数据”; // 输入数据

[按钮点击]

我的代码:

protected void Button1_Click(object sender, EventArgs e)
{
    con = new SqlConnection();
    con.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
    string value = DropDownList4.SelectedValue.ToString();  // Get the dropdown value 
    int count = 0;
    int.TryParse(value, out count);  // cast the value to integer 
    for (int i = 0; i < count; i++)  // iterate it for the N times 
    {
        SqlCommand insert = new SqlCommand("insert into Test(Name, Username) values(@Name, @Username)", con);
        insert.Parameters.AddWithValue("@Name", TextBox1.Text);
        insert.Parameters.AddWithValue("@Username", TextBox2.Text);
        try
        {
            con.Open();
            insert.ExecuteNonQuery();
        }
        catch
        {
            con.Close();
        }
    }
    GridView1.DataBind();
}

此代码无法在数据库中正确插入数据。当我选择 dropdwn-list value 3 时,行插入了 2 次。选择5时,插入3次。

【问题讨论】:

  • 这是 wpf 还是 winforms 应用程序?是否为 DropDownList 设置了 ValuePath 和 DisplayPath?
  • i &lt;= count怎么样
  • 将同一行插入数据库超过一次是错误的。数据库表中的行应该是唯一的。
  • 另外,您正在使用 c# 和 Sql 服务器。使用表值参数而不是多个插入语句。
  • 您的代码将插入相同的 Name 和 UserName 的次数等于从下拉列表中选择的值...这是您真正期望的吗?

标签: c#


【解决方案1】:

您仅在 catch 块中关闭连接。 这就是发生的事情。 在第 1 次迭代中插入值但未关闭连接,在第 2 次迭代中发生异常并关闭连接。在第 3 次迭代中再次插入值,依此类推。 这是更新的代码

    protected void Button1_Click(object sender, EventArgs e)
    {
        con = new SqlConnection();
        con.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();

        string value = DropDownList4.SelectedValue.ToString();  // Get the dropdown value 
        int count = 0;
        int.TryParse(value, out count);  // cast the value to integer 

        for (int i = 0; i < count; i++)  // iterate it for the N times 
        {

            SqlCommand insert = new SqlCommand("insert into Test(Name, Username) values(@Name, @Username)", con);
            insert.Parameters.AddWithValue("@Name", TextBox1.Text);
            insert.Parameters.AddWithValue("@Username", TextBox2.Text);

            try
            {
                con.Open();
                insert.ExecuteNonQuery();

            }
            catch
            {
                i--;
            }
            finally
            {
                con.Close();
            }    
        }
        GridView1.DataBind();

    }

【讨论】:

  • 很高兴能为您提供帮助 :) 如果解决了您的问题,请接受答案
猜你喜欢
  • 2023-03-11
  • 2017-01-13
  • 2011-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-04
  • 1970-01-01
相关资源
最近更新 更多