在C#转换字符串控件名 [英] converting string to a control name in C#

查看:479
本文介绍了在C#转换字符串控件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:结果
查找




假设我们有4个文本框(和一个按钮):




textBox1的:(这里要输入的名称在这里我们要改变
背景文本框)



TextBox2中:()



textBox3 :( )



textBox4:()




在我们的第一个文本框,我们进入。任何其他的文本框的名称,我们点击一​​个按钮时 - backrground将发生相应的变化。



一般情况下我做这样的事情:

 私人无效的button1_Click(对象发件人,EventArgs五)
{
串VARIABLENAME = textBox1.Text();

如果(VARIABLENAME ==textBox1的)
{
textBox1.BackColor = Color.Black;
}
,否则如果(VARIABLENAME ==TextBox2中)
{
textBox2.BackColor = Color.Black;
}
,否则如果(VARIABLENAME ==textBox3)
{
textBox3.BackColor = Color.Black;
}
,否则如果(VARIABLENAME ==textBox4)
{
textBox4.BackColor = Color.Black;
}
}



另一种方式 - 更简单办法做同样的操作将是这样的:

 私人无效的button1_Click(对象发件人,EventArgs五)
{
串VARIABLENAME = textBox1.Text();
variableName.BackColor = Color.Black;
}



而这一切!所以我的问题是:



是否有可能将字符串转换为显示例子中的控件名称


解决方案

A 非常乐观办法是

 这一点。 Controls.Find(变量名,真)[0] .BackColor 


Possible Duplicate:
Find a control in C# winforms by name

Imagine that we have 4 textBoxes (and a button):

textBox1:( Here we must enter the name of the textBox where we want to change background)

textBox2:()

textBox3:()

textBox4:()

In our first textbox we enter a name of any other TextBox and when we click on a button - backrground will change accordingly.

Normally I'd do something like this:

private void button1_Click(object sender, EventArgs e)
{
string variableName = textBox1.Text();

if (variableName == "textBox1")
{
    textBox1.BackColor = Color.Black;
}
else if (variableName == "textBox2")
{
    textBox2.BackColor = Color.Black;
}
else if (variableName == "textBox3")
{
    textBox3.BackColor = Color.Black;
}
else if (variableName == "textBox4")
{
    textBox4.BackColor = Color.Black;
}
}

Another way - much simpler way do the same operation would be this:

private void button1_Click(object sender, EventArgs e)
{
    string variableName = textBox1.Text();
    variableName.BackColor = Color.Black;
}

And that's all! So my question is:

Is it possible to convert strings to "control names" as showed in example?

解决方案

A very optimist approach would be

this.Controls.Find("variableName", true)[0].BackColor

这篇关于在C#转换字符串控件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆