启用动态文本框检查动态复选框在C#

问题描述:

在这里我创建一个文本框及其相应的复选框。我需要的是......我想启用文本框,当我选中该复选框 注:文本框最初是被禁用启用动态文本框检查动态复选框在C#

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 
    } 
} 

如何:

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来检索控件,然后启用它。

+0

哪里把这段代码 – 2015-02-23 11:48:06

+0

在你chkDynamic_CheckedChanged事件 – 2015-02-23 11:49:55

+0

了以下错误:无法识别的转义序列 – 2015-02-23 11:51:28

对于动态(不回发),你会需要你的aspx页面或jQuery的上使用AJAX(的UpdatePanel),至少它更容易这样

+0

ajax回发,但不会刷新整个页面。他没有说他不想回帖 – Liran 2015-02-23 12:01:12

这是一个非常肮脏的解决方案,但它为您挑选它,并使它成为一个生产解决方案:

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; 
    } 
} 
+0

没有用......没有任何事情发生 – 2015-02-23 12:16:30

+0

做的复选框回帖? 当你点击处理程序时,它执行正常还是有任何异常? – Liran 2015-02-23 12:19:04