【发布时间】: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 <= count怎么样 -
将同一行插入数据库超过一次是错误的。数据库表中的行应该是唯一的。
-
另外,您正在使用 c# 和 Sql 服务器。使用表值参数而不是多个插入语句。
-
您的代码将插入相同的 Name 和 UserName 的次数等于从下拉列表中选择的值...这是您真正期望的吗?
标签: c#