它没有显示错误,
但是这些值没有插入到sql server中.....
我们如何从EventDuration_DDL_SelectedIndexChanged()
访问Wizard_buttonClick()中动态生成的标签和复选框? protected void EventDuration_DDL_SelectedIndexChanged(object sender, EventArgs e)
{
int n = Int32.Parse(EventDuration_DDL.SelectedItem.ToString());
for (int i = 0; i < n; i++)
{
Label NewLabel = new Label();
NewLabel.ID = "Label" + i;
var eventDate = Calendar1.SelectedDate.Date.AddDays(i);
NewLabel.Text = eventDate.ToLongDateString();
CheckBox newcheck = new CheckBox();
newcheck.ID = "CheckBox" + i;
newcheck.CheckedChanged += new EventHandler(this.CheckBox_CheckedChanged);
this.Labeldiv.Controls.Add(new LiteralControl("<span class='h1size'>"));
this.Labeldiv.Controls.Add(NewLabel);
this.Labeldiv.Controls.Add(new LiteralControl("</span>"));
this.Labeldiv.Controls.Add(new LiteralControl("<div class='make-switch pull-right' data-on='info'>"));
this.Labeldiv.Controls.Add(newcheck);
this.Labeldiv.Controls.Add(new LiteralControl("</div>"));
this.Labeldiv.Controls.Add(new LiteralControl("<br/>"));
}
}
protected void Wizard1_FinishButtonClick(object sender, WizardNavigationEventArgs e)
{
con.Open();
var label = Labeldiv.FindControl("Label1") as Label;
var checkbox = Labeldiv.FindControl("CheckBox1") as CheckBox;
using (SqlCommand cmd2 = new SqlCommand("insert into EventDays(EventDay,EventStatus)values(@EventDay,@EventStatus)", con))
{
var paramDay = cmd2.Parameters.Add("@EventDay", SqlDbType.DateTime);
var paramStatus = cmd2.Parameters.Add("@EventStatus", SqlDbType.Int);
if (label != null)
{
paramDay.Value = label;
paramStatus.Value = checkbox.Checked ? 1 : 0;
cmd2.ExecuteNonQuery();
}
}
con.Close();
}
答案 0 :(得分:2)
显示错误是因为您在循环中多次添加参数。参数名称必须是唯一的 更改代码,以便从循环中创建参数,并在循环中设置值:
using (SqlCommand cmd2 = new SqlCommand("insert into EventDays(EventDay,EventStatus)values(@EventDay,@EventStatus)", con))
{
var paramDay = cmd2.Parameters.Add("@EventDay", SqlDbType.DateTime);
var paramStatus = cmd2.Parameters.Add("@EventStatus", SqlDbType.Int);
for (int i = 0; i < n; i++)
{
Label NewLabel = new Label();
NewLabel.ID = "Label" + i;
var eventDate = Calendar1.SelectedDate.Date.AddDays(i);
NewLabel.Text = eventDate.ToLongDateString();
NewLabel.CssClass = "h1size";
CheckBox newcheck = new CheckBox();
newcheck.ID = "CheckBox" + i;
this.Labeldiv.Controls.Add(NewLabel);
this.Checkboxdiv.Controls.Add(newcheck);
this.Labeldiv.Controls.Add(new LiteralControl("<br/>"));
paramDay.Value = eventDate;
paramStatus.Value = newCheck.Checked ? 1 : 0;
cmd2.ExecuteNonQuery();
}
}
该示例假定EventDate是DateTime而EventStatus是Int,您可能需要调整数据类型。根据执行命令的次数,您可以在添加参数后运行cmd2。Prepare()。
此外,using语句确保以适当的方式处理SqlCommand对象。
答案 1 :(得分:0)
如果移动
怎么办?SqlCommand cmd2 = new SqlCommand("insert into EventDays(EventDay,EventStatus)values(@EventDay,@EventStatus)", con);
在循环内?
更改
cmd2.Parameters.AddWithValue("@EventStatus", newcheck.Checked ?? 1:0);