2012-10-13 145 views
1

可能重复:
C# Text don’t display on another form after double clicking an item in listbox编辑标签控制

我在C#初学者。每当用户单击按钮btnHighbtnLow(这些按钮位于mainForm)时,我想编辑一个标签lblText,其格式为subForm,其他格式为mainForm

For btnHigh_Click event --> lblText should have text "high" 
For btnLow_Click event --> lblText should have text "low" 

我尝试下面的代码:(不工作

btnHigh_Click事件

 subForm sf = new subForm(); 
     sf.ShowDialog(); 
     sf.lblText.Text = "High"; // lblText --> modifier is public 

什么,我做错了什么?

请帮忙
在此先感谢。

回答

2

你需要显示窗体之前先改变值,

subForm sf = new subForm(); 
    sf.lblText.Text = "High"; 
    sf.ShowDialog(); 
+0

没关系,因为'Text'是一个属性,它在更改时强制更新GUI – 2012-10-13 09:28:46

+1

@Nacereddine他说'lblText'是公开的。 –

+0

@JohnWoo我刚刚读到......我需要更多的咖啡。 – Nasreddine

0

你可以为子窗体创建公共财产:

,并设置该属性上的加载方式:

public subForm() 
     { 
      InitializeComponent(); 
    lblText.Text=lblText; 
     } 

和:

subForm sf = new subForm(); 
sf.lblText = "High"; 
sf.ShowDialog(); 
1

你写了什么问题

subForm sf = new subForm(); 
sf.ShowDialog(); 
sf.lblText.Text = "High"; // lblText --> modifier is public 

ShowDialog方法阻止目前的形式并打开另一个。这会导致行 sf.lblText.Text = "High";在您的subForm关闭后“运行”。

做到这一点的最好办法,是不是让你的文本框为public,但是你可以在构造类似,可提供数据:

子窗体类中添加构造函数:

public subForm(string strText) 
{ 
    InitializeComponent(); 
    this.lblText.Text = strText; // Must be after the InitializeComponent method 
} 

在主叫子窗体写:

subForm sf = new subForm ("High");    
sf.ShowDialog(); 

这是相关的方式来做到这一点。
它更好地避免使用公共许可这种事情。因为subForm中的所有“世界”都不需要知道它已经标记为lblText,并且用于管理对subForm数据的访问。