简体   繁体   中英

Checkbox event on IEnumerable box

I'm making a c# windows form that from an IEnumerable list of item must create a checkbox and a Textbox for every item, and so far I hav made it without problem. Every textbox and every checkbox have a different name from a Name+counter of the rotation.

I would like to make an event that if I uncheck for example the Chkbox1 make the txtbox1 not editable without know How many checkbox I can have.

I'm a little bit newbie in c#.

Use a Dictionary to store the relationship between CheckBox and TextBox . A tag property can also do this, but I think it is ugly.

        //make the dict global, so can access in event handler
        private Dictionary<CheckBox, TextBox> chkTbRelations;

        private void Form1_Load(object sender, EventArgs e)
        {
            chkTbRelations = new Dictionary<CheckBox, TextBox>();
            //simulate your IEnumerable
            foreach (int i in Enumerable.Range(1, 5))
            {
                CheckBox chk = new CheckBox();
                TextBox tb = new TextBox();
                //add other properties such as Size, Location here
                // Controls.Add ...
                // tb.Tag = chk;
                chkTbRelations.Add(chk, tb);
                chk.CheckedChanged += Chk_CheckedChanged;
            }
        }

        private void Chk_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox chk = sender as CheckBox;
            TextBox tb = chkTbRelations[chk];
            //tb = chk.Tag as TextBox;
            tb.Enabled = chk.Checked;
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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