从另一个类C#获取文本框的值
问题描述:
让我们说我有一个名为Form1在其文本框和按钮的形式。
Let's say I have a form named Form1 with textBox and button in it.
我想从按钮点击另一个类的文本框的值。
我试图像这样做,但它不工作:
I want to get the textBox value from another class on button click. I'm trying to do it like this, but it doesn't work:
class Main
{
public void someMethod()
{
Form1 f1 = new Form1();
string desiredValue = f1.textBox.Text;
}
}
请原谅我的愚蠢的问题,但我在C#相当新的,不能让这件事的工作。
Forgive me for the dumb question, but I'm pretty new in C# and can't get this thing to work.
答
您需要创建另一个去寻找打开Form1中,而不是Form1上,创建以下类
You need to find the opened Form1 instead of creating another Form1, create the following class
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?");
}
}
}
在您点击按钮的方法然后
Then in your button click method
private void button1_Click(object sender, EventArgs e)
{
Class1 c = new Class1();
c.someMethod();
}