从另一个类C#获取文本框的值 [英] C# Get textBox value from another class

查看:1105
本文介绍了从另一个类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();
}

这篇关于从另一个类C#获取文本框的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆