2013-07-27 53 views
3

我有這個method這些textboxesSUM價值觀,我想改善它,如果任何這些textboxes的是empty我想插入它"0"這可是我沒有」 t知道在哪裏,以及如何使它像我想要的那樣工作。我很長時間以來一直在想這個,有人會告訴我一些事嗎?當一個文本框爲空,如何輸入一個默認值

void vypocti_naklady() 
    { 
     double a, b,c,d,e,f,g,h; 
     if (
      !double.TryParse(p_ub_s.Text, out a) || 
      !double.TryParse(p_poj_s.Text, out b) || 
      !double.TryParse(p_jin_s.Text, out c) || 
      !double.TryParse(p_dop_s.Text, out d) || 
      !double.TryParse(p_prov_s.Text, out e) || 
      !double.TryParse(p_pruv_s.Text, out f) || 
      !double.TryParse(p_rez_s.Text, out g) || 
      !double.TryParse(p_ost_s.Text, out h) 
     ) 
     { 
      naklady.Text = "0"; 
      return; 
     } 

     naklady.Text = (a+b+c+d+e+f+g+h).ToString(); 
    } 

感謝大家的幫助和時間。

+1

的WinForms或WPF? – sircodesalot

+0

@sircodesalot WinForms,謝謝你的時間。 – Marek

回答

4

你可以讓一個文本框驗證的事件(因爲如果你空只需要插入0,而不是保留焦點),以及訂閱的所有其他文本框到文本框驗證的事件。

例如:你有5個文本框認購(通過點擊例如TextBox1的屬性窗口|事件並雙擊驗證),併爲其他文本框訂閱他們的驗證事件的那一個,然後它裏面把這個:

private void textBox1_Validated(object sender, EventArgs e) 
{ 
    if (((TextBox)sender).Text == "") 
    { 
     ((TextBox)sender).Text = "0"; 
    } 
} 
1
private double GetValue(string input) 
{ 
    double val; 

    if(!double.TryParse(input,out val)) 
    { 
    return val; 
    } 

    return 0; 
} 

var sum = this.Controls.OfType<TextBox>().Sum(t => GetValue(t.Text)); 

嘗試以上操作。剛上的文本框父運行OfType(父母可能是形式本身)

這將計算任何無效的輸入爲0

1

試試這個:

// On the textboxes you want to monitor, attach to the "LostFocus" event. 
textBox.LostFocus += textBox_LostFocus; 

這種監視時TextBox已失去焦點(已被點擊離開)。如果達到,然後運行該代碼:

static void textBox_LostFocus(object sender, EventArgs e) { 
    TextBox theTextBoxThatLostFocus = (TextBox)sender; 

    // If the textbox is empty, zeroize it. 
    if (String.IsNullOrEmpty(theTextBoxThatLostFocus.Text)) { 
     theTextBoxThatLostFocus.Text = "0"; 
    } 
} 

如果效果你看TextBox.LostFocus事件。然後,當使用點擊框離開時,它將運行textBox_LostFocus。如果TextBox爲空,則我們用零替換該值。

1

另一種方法是不直接使用TextBox文本並解析它,而是綁定到一個屬性並使用它們。該Binding本身會做解析和驗證,讓你的變量總是乾淨,以備使用。

public partial class Form1 : Form 
{ 
    // Declare a couple of properties for receiving the numbers 
    public double ub_s { get; set; } 
    public double poj_s { get; set; } // I'll cut all other fields for simplicity 

    public Form1() 
    { 
     InitializeComponent(); 

     // Bind each TextBox with its backing variable 
     this.p_ub_s.DataBindings.Add("Text", this, "ub_s"); 
     this.p_poj_s.DataBindings.Add("Text", this, "poj_s"); 
    } 

    // Here comes your code, with a little modification 
    private void vypocti_naklady() 
    { 
     if (this.ub_s == 0 || this.poj_s == 0 /*.......*/) 
     { 
      naklady.Text = "0"; 
      return; 
     } 
     naklady.Text = (this.ub_s + this.poj_s).ToString(); 
    } 
} 

你只是性能,已經安全地輸入爲double工作而忘記了格式化和解析。您可以通過將所有數據移動到ViewModel類並將邏輯放在那裏來改善這一點。理想情況下,你可以通過數據綁定到它也適用同樣的想法到輸出TextBox,但是對於工作,你必須實現INotifyPropertyChanged所以綁定知道什麼時候更新UI。

相關問題