添加在C#Windows窗体具有相同名称不同的控件窗体、控件、名称、不同

2023-09-06 23:03:49 作者:想把数学灭了的菇凉

我在C#中的窗口在工作窗体应用程序中,我将具有相同名称的 3不同的控件(一个按钮,一个文本框和放大器;一个Label)以我的形式。

为什么有错误button4_Click?

code:

 私人无效的button1_Click(对象发件人,EventArgs的)
 {
        文本框my​​Control =新文本框();
        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.

vs2010 Visual Studio 创建windows窗体应用程序的具体操作流程

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.