C# 在 form1.cs 和 program.cs 之间传递数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15167467/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Passing data between form1.cs and program.cs
提问by krikara
I know this is really basic, but I couldn't find any guides/tutorials on how to do this between MSDN, Google searches, and stackoverflow.
我知道这真的很基础,但我找不到关于如何在 MSDN、Google 搜索和 stackoverflow 之间执行此操作的任何指南/教程。
I created a new Windows Form Application and here I have Program and Form1 where Form1 owns 2 text boxes and buttons.
我创建了一个新的 Windows 窗体应用程序,这里有 Program 和 Form1,其中 Form1 拥有 2 个文本框和按钮。
Button1 is supposed to take the string from Text1 and send it to program.cs where the string gets edited and sent back to Form1. Then Button2 reveals the new string in Text2.
Button1 应该从 Text1 获取字符串并将其发送到 program.cs,在那里字符串被编辑并发送回 Form1。然后 Button2 显示 Text2 中的新字符串。
I got as far as obtaining the string from the Text1 (with Button1), but cannot figure out how to send it to program.cs so it can be processed. What exactly am I supposed to do to pass data between the two?
我从 Text1(使用 Button1)获取字符串,但无法弄清楚如何将其发送到 program.cs 以便对其进行处理。我到底应该怎么做才能在两者之间传递数据?
I'm not sure if this is the right start, but I created a myForm in attempts to get the string sent over. But how do I send it back?
我不确定这是否是正确的开始,但我创建了一个 myForm 以尝试将字符串发送过来。但是我怎么寄回去呢?
In Program.cs:
在 Program.cs 中:
static Form1 myForm;
[STAThread]
static void Main()
{
string s1, s2;
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
myForm = new Form1();
Application.Run(myForm);
s1 = myForm.sendOver();
}
采纳答案by Servy
You effectively can't. Application.Run(myForm);
will block until your form is closed, so it's no longer appropriate to be getting data from it, or giving data to it.
你实际上不能。 Application.Run(myForm);
将阻塞,直到您的表单关闭,因此不再适合从中获取数据或向其提供数据。
In virtually all winform programs you shouldn't ever be modifying program.cs. While you can occasionally get it to work, it's rarely desirable from a design perspective.
在几乎所有的 winform 程序中,您都不应该修改 program.cs。虽然您偶尔可以让它工作,但从设计的角度来看,它很少是可取的。
If you want to do processing based on the result of your from, you should most likely be creating an entirely new class, separate from either of these. Call a method from that class (creating an instance of it if appropriate) when appropriate (this may be when a submit button is clicked, in the form closed event handler, etc.).
如果您想根据 from 的结果进行处理,您很可能应该创建一个全新的类,与其中任何一个分开。在适当的时候从该类调用一个方法(如果合适,创建它的一个实例)(这可能是在点击提交按钮时,在表单关闭事件处理程序中,等等)。
回答by mustafa ?ztürk
static Form1 myForm;
[STAThread]
//we need a holder
//you can access static classes from your forms
public static class myCls {
public static string myStr;
static void myFunc(string str) {
myStr = str; //or whatever
}
}
static void Main()
{
//string s1, s2; //you don't need these
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
myForm = new Form1();
Application.Run(myForm);
//s1 = myForm.sendOver(); //you won't use this
}
your form1 must contain:
您的 form1 必须包含:
//change your holder's content whereever you want
void Button1_Click() {
myCls.myFunc("string");
}
your form2 must contain:
您的 form2 必须包含:
//then call your holder's content whereever you want
void Button1_Click() {
Text1.Text = myCls.myStr;
}
回答by Alireza Noori
A little while ago I've answered an old question which asked how to pass data between two different forms. The answer applies for your situation too. Just pick the one that fits your needs.
不久前,我回答了一个老问题,该问题询问如何在两种不同形式之间传递数据。答案也适用于您的情况。只需选择一款适合您的需求即可。
1- (Not recommended if there's too many parameters) Passing data through the constructor.
1-(如果参数太多,不推荐)通过构造函数传递数据。
private void ShowForm(int a, string b, double c)
{
Form2 frm = new Form2(a, b, c);
frm.ShowDialog();
}
2- Using public fields of target class. (NOT RECOMMENDED AT ALL)
2- 使用目标类的公共字段。(完全不推荐)
private void ShowForm(int a, string b, double c)
{
Form2 frm = new Form2();
frm.intval = a;
frm.strval = b;
frm.doubleval = c;
frm.ShowDialog();
}
3- Using properties.
3- 使用属性。
private void ShowForm(int a, string b, double c)
{
Form2 frm = new Form2();
frm.IntValue = a;
frm.StringValue = b;
frm.DoubleValue = c;
frm.ShowDialog();
}
4- Using tags.
4- 使用标签。
private void ShowForm(int a, string b, double c)
{
Form2 frm = new Form2();
frm.SomeTextBox.Tag = a;
frm.SomeTextBox2.Tag = b;
frm.SomeTextBox3.Tag = c;
frm.ShowDialog();
}
5- Using delegates. (This one is a little bit tricky).
5- 使用代表。(这个有点棘手)。
//in Form2
public delegate void PassValues(int a, string b, double c);
public PassValues passVals;
private void PassDataThroughDelegate(int a, string b, double c)
{
if(passVals != null)
passVals(a,b,c);
}
//in Form1
private void ShowForm(int a, string b, double c)
{
Form2 frm = new Form2();
frm.passVals = new Form2.PassValues(UseData);
frm.ShowDialog();
}
private void UseData(int a, string b, double c)
{
}
My personal favorite ones are the properties, delegates and in some rare cases constructors.
我个人最喜欢的是属性、委托和在极少数情况下的构造函数。
Alternatively, you can create a static class , put some properties in it, then use it in other forms. This is really helpful if all of your forms need to share some information. Since this is not a way to Pass data between the forms, I did not mention this method in those above.
或者,您可以创建一个静态类,将一些属性放入其中,然后以其他形式使用它。如果您的所有表单都需要共享某些信息,这将非常有用。由于这不是在表单之间传递数据的一种方式,所以我在上面的那些中没有提到这种方法。
Update
更新
The above lists the methods to pass data between two classes (in this case forms). However, after reading your question and your comments I can recommend this:
上面列出了在两个类(在本例中为表单)之间传递数据的方法。但是,在阅读了您的问题和评论后,我可以推荐以下内容:
For this particualr case:
对于这种特殊情况:
- Open form designer in the visual studio.
- Double click on the button1. (This will generate an event handler for button1's click event).
Fill the function like this:
private void button1_Click(object sender, EventArgs e) { textBox2.Text = ChangeString(textBox1.Text); } private string ChangeString(string str) { string result = "do some stuff to " + str; return result; }
- 在视觉工作室中打开表单设计器。
- 双击按钮 1。(这将为 button1 的 click 事件生成一个事件处理程序)。
像这样填充函数:
private void button1_Click(object sender, EventArgs e) { textBox2.Text = ChangeString(textBox1.Text); } private string ChangeString(string str) { string result = "do some stuff to " + str; return result; }
Here the ChangeString
function is essentially doing what you want the Program.cs
to do. Just add your functionality to it. If what you want it to do is more complex, you could create a class and add the functionality to that class.
这里的ChangeString
函数本质上是在做你想要Program.cs
做的事情。只需将您的功能添加到它。如果你想让它做的更复杂,你可以创建一个类并将功能添加到该类中。
What I recommend for you in general:
我一般为您推荐的内容:
I think you should take some OO (Object Oriented) classes or read some books. You should get familiar with the concepts of OO and plan what you're supposed to do, before actually doing it. Also, you should read about the inner layers of .Net and C# and know what is the purpose of each part of the programs. I'd go with Console apps first and then go to the Winforms and other UI principles.
我认为您应该参加一些 OO(面向对象)课程或阅读一些书籍。在实际执行之前,您应该熟悉 OO 的概念并计划您应该做什么。此外,您应该了解 .Net 和 C# 的内层,并了解程序每个部分的目的。我会先使用控制台应用程序,然后再使用 Winforms 和其他 UI 原则。
That said, I should quickly say that the Program.cs
is just behaving as an entry point for your program. You shouldn't try to add logic to that class and try to keep the implementation of each class to itself. Try to separate the things each class can do to avoid complicated designs.
也就是说,我应该很快说,Program.cs
它只是作为您程序的入口点。您不应该尝试向该类添加逻辑并尝试将每个类的实现保留为自身。尝试将每个类可以做的事情分开,以避免复杂的设计。
I hope this helps you get started.
我希望这可以帮助您入门。