请问在C#中,如何调用通过动态方法添加的textbox的text值?

2024-12-23 14:30:06
推荐回答(3个)
回答1:

1.建议你将需要隐藏的文本框在设计器上直接创建,并放进一个Panel里面,然后要显示或隐藏直接操作这个Panel,这样就不会有你的问题了。
2.如果非要动态查找,可以遍历窗体的Controls集合进行查找。上面同学说的FindControl是WebForm才有的方法,在WinForm中没有。

回答2:

你的计算按钮为什么不用而要用ListBox的事件呢?用按钮来触发计算事件,取2个文本框内容和ListBox的选项,然后判断后把结果放在第三个文本框里
你的addbtn方法如果无限次的用,那窗体不是会重复添加无数个文本框了吗

回答3:

public void TXT(string txt1Value,string txt2Value,string lab1Value)
{

Control[] controls = this.Controls.Find("txt1", false);
if (controls.Length != 0)
{
this.Controls.RemoveByKey("txt1");
}
controls = this.Controls.Find("txt2", false);

if (controls.Length != 0)
{
this.Controls.RemoveByKey("txt2");
}

controls = this.Controls.Find("txt3", false);

if (controls.Length != 0)
{
this.Controls.RemoveByKey("txt2");
}

controls = this.Controls.Find("lab1", false);
if (controls.Length != 0)
{
this.Controls.RemoveByKey("lab1");
}
TextBox txt1;
txt1 = new TextBox();
txt1.Name = "txt1";
txt1.Location = new Point(20, 20);
txt1.Size = new Size(50, 20);
txt1.Text = txt1Value;
this.Controls.Add(txt1);

TextBox txt2;
txt2 = new TextBox();
txt2.Name = "txt2";
txt2.Text = txt1.Text;
txt2.Location = new Point(100, 20);
txt2.Size = new Size(50, 20);
txt2.Text = txt2Value;
Console.WriteLine(txt2.Text);
this.Controls.Add(txt2);

TextBox txt3;
txt3 = new TextBox();
txt3.Name = "txt3";
txt3.Location = new Point(180, 20);
txt3.Size = new Size(50, 20);
this.Controls.Add(txt3);
Label lab1;
lab1 = new Label();
lab1.Name = "lab1";
lab1.Location = new Point(75, 25);
lab1.Size = new Size(50, 25);
lab1.Text = lab1Value;
this.Controls.Add(lab1);
Label lab2;
lab2 = new Label();
lab2.Location = new Point(160, 25);
lab2.Size = new Size(50, 25);
lab2.Text = "=";
this.Controls.Add(lab2);

}
public void addbtn()
{
Button btncaculate;
btncaculate = new Button();
btncaculate.Location = new Point(50, 50);
btncaculate.Text = "计算";
btncaculate.Size = new Size(50, 50);
this.Controls.Add(btncaculate);

}

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string item = this.listBox1.SelectedItem as string;
if ("加法" == item)
{
TXT("1", "2", "+");
}
else
{
TXT("3", "4", "-");
}

addbtn();
}

给个采纳吧,代码都给你写了