简体   繁体   中英

Can you use a string in the name of the control when setting its property?

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?

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();
    }
}

you can use the controls collection of the Form Object

        var i = this.Controls.IndexOfKey("panel" + text);
        if(i != -1) this.Controls[i].BringToFront();

The wright syntax is

panel1.Controls[(text)]

where text is your string variable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM