这里我正在创建一个文本框及其相应的复选框。我需要的是…我想在选中复选框时启用文本框注意:文本框最初被禁用
for (int i = 0; i < count; i++)
{
TableRow row = new TableRow();
for (int j = 0; j < 1; j++)
{
TableCell cell = new TableCell();
CheckBox chk = new CheckBox();
TextBox txt_ele = new TextBox();
txt_ele.ID = "elective" + i;
txt_ele.Enabled = false;
chk.ID = "chk_" + i.ToString();
chk.Text = "Has Elective Subjects";
chk.AutoPostBack = true;
cell.Controls.Add(chk);
cell.Controls.Add(txt_ele);
row.Cells.Add(cell);
chk.CheckedChanged += new System.EventHandler (chkDynamic_CheckedChanged);
}
table.Rows.Add(row);
this.NumberOfControls++;
}
page.Form.Controls.Add(表);
复选框选中的事件如下
protected void chkDynamic_CheckedChanged (object sender, EventArgs e)
{
CheckBox lb = (CheckBox)sender;
if (lb.Checked)
{
//how to do here
}
}
对于动态(无回发),您需要在aspx页面或jQuery上使用AJAX(UpdatePanel),至少这样更容易
这是一个非常肮脏的解决方案,但它是由您来挑选并使其成为生产解决方案:
protected void chkDynamic_CheckedChanged(object sender, EventArgs e)
{
CheckBox lb = (CheckBox)sender;
if (lb.Checked)
{
((TextBox)lb.Parent.FindControl("elective" + lb.ID.Replace("chk_", string.Empty))).Enabled = true;
}
}
怎么样:
protected void chkDynamic_CheckedChanged (object sender, EventArgs e)
{
CheckBox lb = (CheckBox)sender;
if (lb.Checked)
{
(Page.FindControlRecursive(
"elective" + System.Text.RegularExpressions.Regex.Match(
lb.ID,
@"(d+)(?!.*d)").ToString())
as System.Web.UI.WebControls.WebControl)
.Enabled = true;
}
}
public static Control FindControlRecursive(this Control Root, string Id)
{
if (Root.ID == Id)
{
return Root;
}
foreach (Control Ctl in Root.Controls)
{
Control FoundCtl = FindControlRecursive(Ctl, Id);
if (FoundCtl != null)
{
return FoundCtl;
}
}
return null;
}
这是匹配复选框id的数字部分,然后使用它来创建文本框id。使用FindControl检索控件,然后启用它。