首页 > 解决方案 > 将文本从一个表单上的文本框中复制到另一个表单上的标签

问题描述

我的应用程序在不同的表单上有一个文本框和一个标签。我想将文本框文本复制到标签。

我尝试了以下代码:

//creating the variable
string vInput = textbox1.Text;

//set label text on the other form
label1.Text = vInput

我该如何解决这个问题?

标签: c#

解决方案


如果我对您的理解正确,您有几个选择。要从另一个类访问变量,您需要将其作为参数传递或使其成为类属性。Broots Waymb 的重复问题链接解释了类属性。

作为参数传递看起来像这样。

public class Form2 {
   //Form2 class constructor
   public Form2(string vInputFromForm1) {
      //your code using passed in string
   }
}

public class Form1 {
   //...
   public void someMethod() {
      string vInput = textbox1.Text;
      Form2 form2 = new Form2(vInput); 
   }
}

如果这些选项都不能解决您的问题,您可能需要编辑您的问题以添加更多信息。正如 Dour High Arch 所提到的,提供错误消息对于首先理解问题大有帮助。


推荐阅读