2013-10-30 55 views
1

我無法獲取彈出對話框的文本框的值。我跟着其他StackOverflow的問題,建議把創建Program.cs中一個公共變量的建議:從對話窗口獲取價值

public static string cashTendered { get; set; } 

然後我建立了我的對話是這樣的:

Cash cashform = new Cash(); 
cashform.ShowDialog(); 

當用戶按下並按鈕,這被稱爲:

 if (isNumeric(textBox1.Text, System.Globalization.NumberStyles.Float)) 
     { 
      Program.cashTendered = textBox1.Text; 
      this.Close(); 
     } 
     else 
     { 
      MessageBox.Show("Please enter a valid amount of cash tendered. E.g. '5.50'"); 
     } 

仍然Program.cashTendered保持空。難道我做錯了什麼?謝謝!

回答

5

對於初學者您的形式稱爲Cash應該使用面向對象的設計。它應該有一個名爲CashEntered或類似decimal而不是字符串的公共屬性。您可以這樣稱呼表單:

using (var cashDialog = new CashDialog()) 
{ 
    // pass a reference to the Form or a control in the Form which "owns" this dialog for proper modal display. 
    if (cashDialog.ShowDialog(this) == DialogResult.OK) 
    { 
     ProcessTender(cashDialog.CashEntered); 
    } 
    else 
    { 
     // user cancelled the process, you probably don't need to do anything here 
    } 
} 

使用靜態變量來保存臨時對話框的結果是一種不好的做法。下面是對話框的更好實現:

public class CashDialog : Form 
{ 
    public decimal CashEntered { get; private set; } 

    private void ok_btn_Clicked 
    { 
     decimal value; 
     if (Decimal.TryParse(cashEntered_txt.Text, out value)) 
     { 
      // add business logic here if you want to validate that the number is nonzero, positive, rounded to the nearest penny, etc. 

      CashEntered = value; 
      DialogResult = DialogResult.OK; 
     } 
     else 
     { 
      MessageBox.Show("Please enter a valid amount of cash tendered. E.g. '5.50'"); 
     } 
    } 
} 
+0

Thanks!完美作品 – Nathan

+0

@Nathan不客氣。這樣,您可以隨時在需要現金輸入的情況下重複使用對話框,甚至可以與其他項目共享該對話框。 –

0

在你想要獲得價值的主窗體上,你會有這樣的代碼;

 var cashTendered; 
     using (var frm = new Cash()) 
     { 
      if (frm.ShowDialog() == DialogResult.OK) 
       cashTendered = frm.GetText() 
     } 

然後你的對話形式,你有這樣的事情:

 public string GetText() 
     { 
       return textBox1.Text; 
     } 

     public void btnClose_Click(object sender, EventArgs e) 
     { 
       this.DialogResult = DialogResult.OK; 
       this.Close(); 
     } 

     public void btnCancel_Click(object sender, EventArgs e) 
     { 
       this.Close(); 
     } 

或者,你可以執行在btnClose_Click事件時,這些線路中的事件的FormClosing代替,如果你不有一個按鈕讓他們點擊'提交'他們的價值。

編輯您可能要添加某種驗證您的文本框中的btnClose事件中,如:

decimal myDecimal; 
if (decimal.TryParse(textBox1.Text, out myDecimal)) 
{ 
     this.DialogResult = DialogResult.OK; 
     this.Close(); 
} 
else 
{ 
    MessageBox.Show("Invalid entry", "Error"); 
    textBox1.SelectAll(); 
}