我在这里创建一个文本框及其相应的复选框。我需要的是...我想在勾选复选框时启用文本框 注意:文本框最初被禁用
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
}
}
答案 0 :(得分:0)
怎么样:
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检索控件然后启用它。
答案 1 :(得分:0)
对于动态(没有回发),你需要在你的aspx页面或jQuery上使用AJAX(UpdatePanel),至少它更容易这样
答案 2 :(得分:0)
这是一个非常肮脏的解决方案,但它可以让你把它拿起来并使它成为一个生产解决方案:
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;
}
}