Winform中通过一个字符串定位到和字符串相等ID的控件(将字符串转换成相应的控件名称)
法一:
string controlName = "控件名称";
foreach (control con in 父容器.Controls)
{
if (con.Name == controlName)
{
///找到控件了;
///然后将其拆箱,就OK了.
}
}
string str = "button" + "1";
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)
//必须已经有button1控件否则会出错
Button btn1 = (Button)this.Controls.Find(str, true)[0];
if (btn1 == button1)
MessageBox.Show(btn1.Text);
朋友说的方法倒能够实现,但如果控件很多,而且每次都要动态判断,性能方面就回受到很大影响,这也不时为一个办法.
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)
{
if (con.Name == controlName)
{
///找到控件了;
///然后将其拆箱,就OK了.
}
}
上面的方法如果在一个窗体里面查找某个控件则父容器就是this如下,如果是其他容器控件则为某容器的ID.
Control.ControlCollection controls = this.Controls;
foreach (Control myControl in controls)
{
if (myControl.Name == "radioButton1")
{
RadioButton radBtn = (RadioButton)myControl;
radBtn.Checked = true;
}
}
foreach (Control myControl in controls)
{
if (myControl.Name == "radioButton1")
{
RadioButton radBtn = (RadioButton)myControl;
radBtn.Checked = true;
}
}
方法二:
CSDN朋友帮助:
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)
其实通过上面的转换btn1和button1是同一个控件了,其他容器控件也有同样的Find方法,这样也不错..
其他更好的方法有待进一步研究...
Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=1650819