gpt4 book ai didi

C# 从另一个类中获取文本框值

转载 作者:行者123 更新时间:2023-11-30 13:09:56 25 4
gpt4 key购买 nike

假设我有一个名为 Form1 的表单,其中包含文本框和按钮。

我想在单击按钮时从另一个类获取文本框值。我正在尝试这样做,但它不起作用:

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();
}

关于C# 从另一个类中获取文本框值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9626187/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com