简体   繁体   English

将变量值从表单复制到类,然后复制到另一个表单

[英]Copy variable value from a form to a class then to another form

I have form1 , class1 and form2 . 我有form1class1form2

What I'm trying to do is to get a text from a textbox in form1 and save it to class1 and then again copy it to form2 from class1 . 我想做的是从form1的文本框中获取文本并将其保存到class1 ,然后再次将其从class1复制到form2

Let me describe via code: 让我通过代码来描述:

class1.cs 将Class1.cs

 public string username;

form1.cs Form1.cs的

class1 user = new class1();
user.username = textbox1.text;

form2.cs form2.cs

 class1 user = new class1();
 label1.text = user.username;

The problem is: When I try to call username variable in form2 it returns blank. 问题是:当我尝试在form2调用username变量时,它返回空白。 It just doesn't work. 就是行不通。 I dont know what I am missing. 我不知道我在想什么。

如果您在表格2中实例化新的class1,则永远不会在label1中获得用户名。

The user in form2 is not the same one that in form1. Form2中的user与Form1中的user不同。 So in form1 your user including a name, and in form2 it including an initialize value (blank). 因此,在form1中,您的user包括一个名称,在form2中,它包括一个初始化值(空白)。 You can pass this user from form1 to form2 by Session or Cookies. 您可以通过Session或Cookies将该user从form1传递到form2。

Make class 1 static. 将第1类设为静态。 You will be able to call the class from any other instantiated objects, increment (or change) your variable and then retrieve it from any other objects. 您将能够从任何其他实例化的对象调用该类,增加(或更改)变量,然后从任何其他对象检索它。 The synchronized part is something that stops two objects from accessing the incrementCounter() method at the same time. 同步部分可以阻止两个对象同时访问incrementCounter()方法。 Something like this: 像这样:

/* This class is thread-safe */
public final class CountHits {
  private static int counter;
  private static final Object lock = new Object();

  public void incrementCounter() {
    synchronized (lock) {
      counter++;
    }
  }
  public int getCounter() {
     return counter;
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM