假设我有一个名为Form1的表单,其中包含textBox和button.
我希望在按钮单击时从另一个类获取textBox值.
我试图这样做,但它不起作用:
class Main { public void someMethod() { Form1 f1 = new Form1(); string desiredValue = f1.textBox.Text; } }
请原谅我这个愚蠢的问题,但我在C#中很新,并且不能让这个东西起作用.
解决方法
您需要找到打开的Form1而不是创建另一个Form1,创建以下类
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; using System.Windows.Forms; namespace WindowsFormsApplication1 { class Class1 { public void someMethod() { TextBox t = Application.OpenForms["Form1"].Controls["textBox1"] as TextBox; Debug.WriteLine(t.Text + "what?"); } } }
然后在按钮单击方法中
private void button1_Click(object sender,EventArgs e) { Class1 c = new Class1(); c.someMethod(); }