如何从另一个类更改标签? c#windows形成视觉工作室

我知道有很multithreading在谈论这个并相信我,我已经看到了所有这些,但我认为我有点慢,无法弄清楚如何做到这一点,所以这就是事情! 我有一个表格

public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button4_Click(object sender, EventArgs e) { adi mYadi= new adi(); adi.paso(); } private void Form1_Load(object sender, EventArgs e) { } public void l8u(string l ) { label8.Text = l; } } 

l8u方法应该更改label8的文本,因此它不能是静态的,因为label8不是静态的(是公共的)而且我有另外这个类

 public class adi :instrucion { private int paso; private int registroD; private int registroO; private int valor; private int vsin; public adi() { paso = 1; } public void setRD(int i){ registroD = i; } public void setR0(int i) { registroO = i; } public void setV(int i) { valor = i; } public int getRD() { return registroD ; } public int getR0() { return registroO; } public int getVf() { return vsin; } public void paso(){ //in this method I need change the value of label8 } } 

方法paso是负责更改label8值的label8但我不能这样做! 我尝试了许多不同的方式,例如做类似的事情

 public void paso() { Form1.l8u(); } 

但这是不可能的,因为Form1只是类的名称而l8u不是静态方法,也尝试将label8设置为公共静态,但是visual studio不喜欢这样,每当我在VS中使用新控件时改变公众静态只是为了公开。

希望你能帮我!

只需将标签的修饰符属性更改为内部或公共,然后调用您的表单并直接更改标签文本。

 Form2 frm = new Form2(); // Form 2 contains label8 and calling in a method (iebuttonclick) of form1 if (List.Count > 0) { frm.Label8.Text = "Someone Loves Me :)"; } else { frm.Label8.Text = "Noone Loves Me :("; } 

以这种方式更改标签不是一个好主意,违反了一些编程范例。 通常,底层业务逻辑类不应该直接操作UI。

表单包含adi的实例。 因此,如果没有将表单的实例(即this )传递给adi构造函数(或者paso方法),那么你就有点沉没了。

最好使用adi可以在需要Form1更改其显示时触发的某种事件。

http://msdn.microsoft.com/en-us/library/aa645739(v=vs.71).aspx

我知道这是2年前,但你不能这样做

 public static void function(label l) { l.Text = "Changed text" } 

然后在表格中

 private void timer_tick(object sender, EventArgs e) { function(label); } 

我也在寻找答案,但我终于找到了如何从另一个类更改form1的标签。

通常Form1.Designer.cs看起来像这样:

  this.label6.AutoSize = true; this.label6.Location = new System.Drawing.Point(59, 174); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(72, 13); this.label6.TabIndex = 16; this.label6.Text = "Output String:"; 

Form1.Designer.cs应该是这样的,所以你可以在另一个类上调用它:

  label8 = new System.Windows.Forms.Label(); label8.AutoSize = true; label8.Location = new System.Drawing.Point(219, 26); label8.Name = "label8"; label8.Size = new System.Drawing.Size(35, 13); label8.TabIndex = 25; label8.Text = "label8"; // // Form1 // this.Controls.Add(label8); 

一些“这个”。 除了Form1.Designer.cs中label8中“this.Controls.Add”的部分之外的文本

你应该从另一个类这样调用它:

 WindowsFormsApplication999.Form1.label8.Text = "your text here."; //This should modify label8.Text. 

编辑:

您还应该在Form1.Designer.cs中修改它

  private System.Windows.Forms.Label label8; 

进入这个:

  public static System.Windows.Forms.Label label8;