C#从另一个类获取textBox值

假设我有一个名为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();
}

相关文章

目录简介使用JS互操作使用ClipLazor库创建项目使用方法简单测...
目录简介快速入门安装 NuGet 包实体类User数据库类DbFactory...
本文实现一个简单的配置类,原理比较简单,适用于一些小型项...
C#中Description特性主要用于枚举和属性,方法比较简单,记录...
[TOC] # 原理简介 本文参考[C#/WPF/WinForm/程序实现软件开机...
目录简介获取 HTML 文档解析 HTML 文档测试补充:使用 CSS 选...