C#从另一个类获取textBox值
发布时间:2020-12-15 19:56:34 所属栏目:百科 来源:网络整理
导读:假设我有一个名为Form1的表单,其中包含textBox和button. 我希望在按钮单击时从另一个类获取textBox值. 我试图这样做,但它不起作用: class Main{ public void someMethod() { Form1 f1 = new Form1(); string desiredValue = f1.textBox.Text; }} 请原谅我这
假设我有一个名为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(); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |