2

I have been creating arrays for different controls as follows, e.g:

private TextBox[] Array_TextBoxes;
private CheckBox[] Array_CheckBoxes;
private RadioButtonList[] Array_radioButton;

Array_TextBoxes= new TextBox[4];
Array_CheckBoxes= new CheckBox[5];
Array_radioButton= new RadioButtonList[10];

Is there any ways of creating them so that I do not need to specify the size/length? I.e. is it possible to make these control arrays variable sized?

Thanks!

1

3 Answers 3

5

Arrays must be assigned a length, if you want to allow for any number of elements use the List class, like this

List<TextBox> textBoxList=new List<TextBox>();

and add controls into this collection

 textBoxList.Add(new TextBox());
Sign up to request clarification or add additional context in comments.

Comments

2

You could start them as lists then convert to array:

Add stuff to these using .Add:

List<TextBox> _TextBoxes = new List<TextBox>();
List<CheckBox> _CheckBoxes =  new List<CheckBox>();
List<RadioButtonList> _RadioButton = new List<RadioButtonList>();

Then convert to arrays:

TextBox[] Array_TextBoxes = List<TextBox> _TextBoxes.ToArray();
CheckBox[] Array_CheckBoxes = List<CheckBox> _CheckBoxes.ToArray();
RadioButtonList[] Array_radioButton = List<RadioButtonList> _radioButton.ToArray();

Or just use lists...

Comments

2

List<>, as others have suggested, is a good idea, but it does have some overhead. You can also do this, if you "use" System.Linq, and assume that the controls variable points to a collection of the controls:

Array_TextBoxes = controls.OfType<TextBox>().ToArray();

Furthermore, if you prefer to have lists instead of arrays, you can do that too:

List<TextBox> textBoxes = controls.OfType<TextBox>().ToList();

Finally, it's often considered poor style to use prefixes like "Array_" in your field and variable names.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.