简体   繁体   English

启用动态文本框以检查c#中的动态复选框

[英]enable dynamic textbox for checking dynamic checkbox in c#

Here i am creating a textbox and its corresponding checkbox. 在这里,我创建一个文本框及其相应的复选框。 what i need is... i want to enable the textbox when i check the checkbox Note: textbox is initially disabled 我需要的是...我想在选中复选框时启用文本框注意:文本框最初被禁用

    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(table); page.Form.Controls.Add(表);

and check box checked event is as follows 和复选框检查事件如下

protected void chkDynamic_CheckedChanged (object sender, EventArgs e)
{
    CheckBox lb = (CheckBox)sender;
    if (lb.Checked)
    {
          //how to do here
    }
}

How about: 怎么样:

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

This is matching the numeric part of the checkbox id and then using it to create the textbox id. 这与复选框ID的数字部分匹配,然后使用它来创建文本框ID。 Using FindControl to retrieve the control and then enabling it. 使用FindControl检索控件然后启用它。

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

this is a very dirty solution but its for you to pick it up and make it a production solution: 这是一个非常肮脏的解决方案,但它可以让你拿起它并使其成为一个生产解决方案:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM