Reputation: 100
I have a list box with a lot of items, and each item is supposed to open a panel next to it. When an item is clicked, it brings it's respective panel to the front (the panels are all positioned in the same place).
I've tried using if statements to check the selected index, but this will result in 1000s of if statements which will end up being confusing.
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
// gets item text
string text = listBox1.GetItemText(listBox1.SelectedItem);
// brings panel to front
panel**the text string goes here**.BringToFront();
}
I'm trying to use a variable to get the text of the selected item and then use this variable in the name of the control (similarly to how you can use variables in strings), but it's not working for me. Is there an alternative way, or is this not possible?
Upvotes: 0
Views: 103
Reputation: 39132
You can search for the control by name with Controls.Find()
. This will find it regardless of how deep it is nested inside other containers:
if (listBox1.SelectedIndex != -1)
{
string ctlName = "panel" + listBox1.SelectedItem.ToString();
Control ctl = this.Controls.Find(ctlName, true).FirstOrDefault();
if (ctl != null)
{
ctl.BringToFront();
}
}
Upvotes: 2
Reputation: 8033
you can use the controls collection of the Form Object
var i = this.Controls.IndexOfKey("panel" + text);
if(i != -1) this.Controls[i].BringToFront();
Upvotes: 1
Reputation: 72
The wright syntax is
panel1.Controls[(text)]
where text is your string variable
Upvotes: -2