[.NET 2]
how should I list a form controls in a Combobox of the same form(like VS designer does)?
I tried:
cboObjectSelection.DataSource = Me.Controls
but this does not work.
Is there a possibility to filter(customize) this list?
[.NET 2]
how should I list a form controls in a Combobox of the same form(like VS designer does)?
I tried:
cboObjectSelection.DataSource = Me.Controls
but this does not work.
Is there a possibility to filter(customize) this list?
You might be able to do it if you set the ComboBox.DisplayMember
to "Name"
but you'd then not get any controls contained in other controls so I think you'd have to get out the names of all the controls (recursively) and insert them into a collection and then pass that as the DataSource
.
I have put the code in a button's click event, you can modify it according to you requirement. Hope this will help you.
private void button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < this.Controls.Count; i++)
{
s = this.Controls[i].GetType().ToString();
comboBox1.Items.Add(s);
}
}
You'll have to iterate each item in the Controls collection and add it to the ComboBox's Items collection. The simplest code would look like this:
For Each c As Control in Me.Controls
cboObjectSelection.Items.Add(c.Name)
Next
The issues here are that Me.Controls
is hierarchical. IE, a the controls inside a Panel on your form will be missed with this case. You would need to add all the Panel's Controls to get EVERYTHING on the form. Which is an ideal application of recursion:
Private Sub AddControls(ByVal Combo As ComboBox, ByVal Control As Control)
For Each c As Control In Control.Controls
Combo.Items.Add(c.Name)
AddControls(Combo, c)
Next
End Sub
To get the control back, you have to do this:
Dim c As Control = Me.Controls.Find(ComboBox1.SelectedItem.ToString(), True)(0)
The second parameter tells the find controls whether to recurse through the hierarchy of controls. The Find method returns an array of controls, hence the (0)
at the end to get the first element. You should be safe here regarding out of bounds exceptions (IE, the Find method doesn't find anything) because everything in the ComboBox will have been added by code a few minutes ago.
Hope this helps!