What happened to control arrays

2019-02-23 10:59发布

问题:

Few years ago I used to program with Visual Basic 6, I was able to create objects with the same name, then differ them by the index. for example, we can create TextBox1 and another TextBox1 but with a different index. now this feature is not available anymore! Currently, I'm using Visual Studio 2012. Is there anyway to manipulate VS2012 to enable that feature again, or is there something similar to it, because it was really helpful.

回答1:

The easier way to accomplish a similar thing today is to place all of these controls in a common parent control. This parent could be a groupbox, a panel, or even the form itself.

So if, say, all of the checkboxes on your form need to be indexed, with no exception, you don't have to do anything special. If just one checkbox is different, you need that checkbox to have a different parent control than your indexed checkboxes. In this case, you could layer a panel control under the checkbox group, or you can layer a panel control under the single checkbox that is different. Either will work.

Later on, you will still not be able to access these checkboxes by index, but you will be able to treat them as a collection. Here's how you can do that:

For Each box As CheckBox In Me.Controls.OfType(Of Checkbox)()
    'Do something with each checkbox
Next

Or if you want to know which ones are checked:

Dim checkedBoxes As IEnumerable(Of Checkbox) = Me.Controls.OfType(Of Checkbox)().Where(Function(b) b.Checked)

If you really want an array of the checkboxes, you can use this technique to get one. Just put code like this in your form's load event:

Dim checkBoxes() CheckBox = Me.Controls.OfType(Of CheckBox)().OrderBy(Function(b) b.Name).ToArray()


回答2:

It's horrible painful now.

MSDN covers this subject now: http://msdn.microsoft.com/en-us/library/aa289500%28v=vs.71%29.aspx

Long live VB6!