[英]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. 我尝试使用if语句检查选定的索引,但这将导致1000的if语句,最终将导致混乱。
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()
. 您可以使用Controls.Find()
按名称搜索 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 您可以使用Form对象的控件集合
var i = this.Controls.IndexOfKey("panel" + text);
if(i != -1) this.Controls[i].BringToFront();
The wright syntax is Wright的语法是
panel1.Controls[(text)] panel1.Controls [(文本)]
where text is your string variable 文本是您的字符串变量
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.