Assign checkboxes to an checkbox-array using a for loop in C#

允我心安 提交于 2019-12-25 03:24:20

问题


I'd like to do this:

CheckBox[] boxarray = new CheckBox[4];
    boxarray[0] = checkBox1;
    boxarray[1] = checkBox2;
    boxarray[2] = checkBox3;
    boxarray[3] = checkBox4;

using a for loop - because I have about 600 checkboxes. I thought about this:

for (int i = 0 ; i<= 600; i++)
    {
    boxes[i] = checkBox[i] ;
    }

But whatever I tried - it didn't work. I hope you know what I mean. Thanks for your help!


回答1:


If you have these CheckBoxes on your form, then you can add them to an array (or List, which would be much easier to do) like that:

List<CheckBox> checkBoxesList = new List<CheckBox>();
foreach (Control ctrl in FormName.Controls)
{
    if (ctrl.GetType() == typeof(CheckBox))
    {
        checkBoxesList.Add(ctrl as CheckBox);
    }
}

Remember, simply writing:
checkBox1, checkBox2
won't make it possible to get them like checkBox[0] - it's not an array, it's just a name with '1' or '2' in the end.




回答2:


Using the current setup, you'll have to use FindControl (assuming ASP.net, winforms and WPF work differently):

for(int i = 0; i <= 600; i++)
{
    boxes[i] = Page.FindControl("checkbox" + i);
}

Update for windows forms: There is actually a method you can use to find all controls of a specific type:

How to get ALL child controls of a Windows Forms form of a specific type (Button/Textbox)?

Here's another option for you. I tested it by creating a sample application, I then put a GroupBox and a GroupBox inside the initial GroupBox. Inside the nested GroupBox I put 3 TextBox controls and a button. This is the code I used (even includes the recursion you were looking for)

public IEnumerable<Control> GetAll(Control control,Type type) {
    var controls = control.Controls.Cast<Control>();
    return controls.SelectMany(ctrl => GetAll(ctrl,type))
                   .Concat(controls)
                   .Where(c => c.GetType() == type); 
}

To test it in the form load event I wanted a count of all controls inside the initial GroupBox

private void Form1_Load(object sender, EventArgs e) {
    var c = GetAll(this,typeof(TextBox));
    MessageBox.Show("Total Controls: " + c.Count());
}

And it returned the proper count each time, so I think this will work perfectly for what you're looking for :)

If you have other checkboxes on your form that you don't want to add, you'll have to use the following method:

for(int i = 0; i <= 600; i++)
{
    boxes[i] = this.Controls.Find("checkbox" + i, true).FirstOrDefault() as CheckBox;
}



回答3:


you are not able to specifiy the name of the checkboxes in the code like you have done, because i wont get changed.

you have to create new instances of CheckBox like:

for (int i = 0 ; i<= 600; i++)
{
    //This will create a new instance of a CheckBox
    CheckBox cb = new CheckBox()

    //At this point the checkbox is empty and not visible anywhere
    //So you have to change some properties:
    cb.Text = "Check me!";
    cb.Top = Ycoord; //you should change this depending on i like +(i*30)
    cb.Left = Xcoord;
    cb.name = "checkbox" + i.toString();
    //To recognize if one of your Checkboxes is checked/unchecked you need to add
    //an event like this (for the event see down below)
    cb.CheckedChanged += checkedChangedEvent;
    //then you need to add the checkbox to your Array
    boxes[i] = cb;
    //to make those checkboxes visible you need to add them to your form
    //or Panel:
    myForm.Controls.Add(cb);
}

The Event:

public void checkedChangedEvent(Object sender, EventArgs e)
{
    MessageBox.Show(((CheckBox)sender).name + " is now Checked == " + ((CheckBox)sender).Checked.toString();
}

you have to specify which Checkbox was Checked/Unchecked by its name, because every CheckBox is firing the same event.

EDIT2:

to get the number of the checkbox you can do something like this in the event:

int cbNumber = 0;
try
{
    cbNumber = System.Convert.toInt32(((CheckBox)sender).name.Replace("checkbox",""));
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message + "\n\n" + ex.StackTrace);
}


来源:https://stackoverflow.com/questions/25605381/assign-checkboxes-to-an-checkbox-array-using-a-for-loop-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!