添加在C#Windows窗体具有相同名称不同的控件 [英] Adding different controls having same names in C# Windows Form
问题描述
我在C#中的窗口在工作窗体应用程序中,我将具有相同名称的 3不同的控件(一个按钮,一个文本框和放大器;一个Label)以我的形式。
为什么有错误button4_Click?
code:
私人无效的button1_Click(对象发件人,EventArgs的)
{
文本框myControl =新文本框();
myControl.Name =显示myControl;
this.Controls.Add(myControl);
}
私人无效button2_Click(对象发件人,EventArgs的)
{
按钮myControl =新按钮();
myControl.Name =显示myControl;
this.Controls.Add(myControl);
}
私人无效button3_Click(对象发件人,EventArgs的)
{
标签myControl =新的Label();
myControl.Name =显示myControl;
this.Controls.Add(myControl);
}
私人无效button4_Click(对象发件人,EventArgs的)
{
((组合框)this.Controls [显示myControl])文本=myCombo。 // 作品
((文本框)this.Controls [显示myControl])文本=会将myText。 // 错误
((标签)this.Controls [显示myControl])文本=myLabel。 // 错误
}
该控件[字符串]索引器返回第一个控制其名称的字符串相匹配。这将是碰运气,与你的code,但你可能有一个组合框已经添加到具有相同名称的形式。接下来的语句去KABOOM因为你不能施放一个ComboBox一个文本框。
当然,也尝试做理智的事情,给这些控件不同的名字。
I am working in C# windows forms application in which I am adding 3 different controls having same name (a button, a textBox & a Label) to my form.
Why there is error in button4_Click?
CODE:
private void button1_Click(object sender, EventArgs e)
{
TextBox myControl = new TextBox();
myControl.Name = "myControl";
this.Controls.Add(myControl);
}
private void button2_Click(object sender, EventArgs e)
{
Button myControl = new Button();
myControl.Name = "myControl";
this.Controls.Add(myControl);
}
private void button3_Click(object sender, EventArgs e)
{
Label myControl = new Label();
myControl.Name = "myControl";
this.Controls.Add(myControl);
}
private void button4_Click(object sender, EventArgs e)
{
((ComboBox)this.Controls["myControl"]).Text = "myCombo"; // works
((TextBox)this.Controls["myControl"]).Text = "myText"; // error
((Label)this.Controls["myControl"]).Text = "myLabel"; // error
}
The Controls[string] indexer returns the first control whose name matches the string. It will be hit and miss with your code but you probably have a ComboBox already added to the form with that same name. The next statements go kaboom because you cannot cast a ComboBox to a TextBox.
Of course, do try to do the sane thing, give these controls different names.
这篇关于添加在C#Windows窗体具有相同名称不同的控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!