Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
191 views
in Technique[技术] by (71.8m points)

c# - Making an indexed control array?

Has C# indexed control arrays or not? I would like to put a "button array" for example with 5 buttons which use just one event handler which handles the index of all this 5 controls (like VB6 does). Else I have to write for each of these 5 buttons one extra event handler. And if I have 100 buttons, I need 100 event handlers? I mean something like that:

TextBox1[i].Text="Example";

It could make coding definitely easier for me to work with control arrays. Now I have seen, that C# at least has no visible array functionality on user controls and no "index" property on the user controls. So I guess C# has no control arrays, or I must each element call by known name.

Instead of giving 100 TextBoxes in a for loop 100 incrementing values, I have to write:

TextBox1.Text = Value1;
TextBox2.Text = Value2;
...
...
TextBox100.Text = Value100;

A lot of more work + all these 100 event handlers each for one additional TextBox extra.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I know I'm a little late to this party, but this solution will work:

Make a global array:

    TextBox[] myTextBox;

Then in your object's constructor, after the call to

    InitializeComponent();

initialize your array:

    myTextBox = new TextBox[] {TextBox1, TextBox2, ... };

Now you can iterate your array of controls:

    for(int i = 0; i < myTextBox.Length; i++)
        myTextBox[i].Text = "OMG IT WORKS!!!";

I hope this helps!

Pete


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...