现在我想将相应的Label文本和checkBox值提取到按钮,即我已经创建了标签& DDL SelectIndexChanged中的CheckBoxes现在我想将它们存储在按钮单击中...如何将它们提取到按钮单击事件中??????
我是根据DDL选择创建的......
<div class="row-fluid" runat="server" id="Labeldiv">
</div>
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;
CheckBox newcheck = new CheckBox();
newcheck.ID = "CheckBox" + i;
this.Labeldiv.Controls.Add(NewLabel);
this.Labeldiv.Controls.Add(newcheck);
}
}
protected void Done_Button_Click(object sender, EventArgs e)
{
con.Open();
int n = Int32.Parse(EventDuration_DDL.SelectedItem.ToString());
for (int i = 0; i < n; i++)
{
string labelId = "Label" + i.ToString();
Label NewLabel = (Label)this.Labeldiv.FindControl(labelId);
string checkBoxId = "Checkbox" + i.ToString();
CheckBox newcheck = (CheckBox)this.Labeldiv.FindControl(checkBoxId);
SqlCommand cmd = new SqlCommand("insert into EventDays(EventDay,EventStatus)values(@EventDay,@EventStatus)", con);
cmd.Parameters.AddWithValue("@EventDay", NewLabel.Text);
cmd.Parameters.AddWithValue("@EventStatus", newcheck.Checked ? "true" : "false");
cmd.ExecuteNonQuery();
}
con.Close();
}
答案 0 :(得分:0)
您可以使用FindControl根据其ID查找控件。以下示例假定您希望根据ComboBox的选择获取所有有效的标签和复选框:
int n = Int32.Parse(EventDuration_DDL.SelectedItem.ToString());
for (int i = 0; i < n; i++)
{
string labelId = "Label" + i.ToString();
Label NewLabel = (Label) this.LabelDiv.FindControl(labelId);
string checkBoxId = "Checkbox" + i.ToString();
CheckBox newcheck = (Checkbox)this.LabelDiv.FindControl(checkBoxId);
}
但是,您应该在页面的OnInit中重新创建控件。有关详细信息,请参阅MSDN上的这篇文章。
正如您在上一个问题中已经说明的那样,静态创建控件并使用Visible属性显示或隐藏控件或使用具有匹配项模板的转发器也可能是一个可行的选项。
这比处理动态控件创建及其副作用要容易得多,并且由于组合框中定义了最大数量的控件,因此可以恕我直言。
答案 1 :(得分:0)
您必须将该代码放在Page_Load()..
中要做到这一点,请参阅以下代码......
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
StartDate_TB.Text = DateTime.Today.ToShortDateString();
EventDuration();
}
private void EventDuration()
{
DateTime dt = DateTime.Parse(StartDate_TB.Text);
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 = dt.AddDays(i);
NewLabel.Text = eventDate.ToLongDateString();
CheckBox newcheck = new CheckBox();
newcheck.ID = "CheckBox" + i;
this.Labeldiv.Controls.Add(new LiteralControl("<div class='row-fluid'>"));
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("</div>"));
this.Labeldiv.Controls.Add(new LiteralControl("<br/>"));
}
}