2012-10-13 143 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數據的訪問。