![](/img/trans.png)
[英]C# Windows Form - How do I assign a double value to a combo box string to then be displayed in a text box?
[英]How to validate if the values of four text box is empty string or not and assign these text box as “0” value if it is empty in C# with minimal code
我在C#中有四個文本框,如果任何文本框的值是:empty string,則必須將其指定為“ 0”。我嘗試了以下似乎冗長的代碼。
if (txtReset1.Text == "")
{
txtReset1.Text = "0";
}
if (txtReset2.Text == "")
{
txtReset2.Text = "0";
}
if (txtReset3.Text == "")
{
txtReset3.Text = "0";
}
if (txtReset4.Text == "")
{
txtReset4.Text = "0";
}
是否有比以上代碼更有效的代碼?
與其重復自己,不如創建一個新方法來處理它:
private void SetEmptyTextBoxToZero(TextBox textBox)
{
if (textBox != null && string.IsNullOrEmpty(textBox.Text)
{
textBox.Text = "0";
}
}
然后,將代碼替換為:
SetEmptyTextBoxToZero(txtReset1);
SetEmptyTextBoxToZero(txtReset2);
SetEmptyTextBoxToZero(txtReset3);
SetEmptyTextBoxToZero(txtReset4);
正如“ Binkan Salaryman”建議的那樣,如果您有很多需要以這種方式處理的文本框,則可以將對它們的引用存儲在列表中,然后對其進行迭代,而不是像上面那樣列出它們:
var textBoxes = new List<TextBox> { txtReset1, txtReset2, txtReset3, txtReset4 };
...
// Option 1: using .ForEach()
textBoxes.ForEach(tb => SetEmptyTextBoxToZero(tb));
// Option 2: using foreach
foreach (var tb in textBoxes)
{
SetEmptyTextBoxToZero(tb);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.