[英]Correct use of logical operator in C#
我有以下If
塊,它在按下表單對象上的命令按鈕時運行。 這應該僅檢查一下上述四個文本框是否為空,如果顯示為空,則顯示一個消息框,然后退出該過程,以便用戶可以更正字段並繼續。
以下是相關代碼:
if (string.IsNullOrWhiteSpace(txtName.ToString()) ||
string.IsNullOrWhiteSpace(txtID.ToString()) ||
string.IsNullOrWhiteSpace(txtSalary.ToString()) ||
string.IsNullOrWhiteSpace(txtERR.ToString()))
{
MessageBox.Show("One or more text fields are empty or hold invalid data, please correct this to continue","Data Error",MessageBoxButtons.OK);
return;
}
我將所有文本字段留為空白,甚至嘗試在其中添加空格字符,但條件代碼未執行。 由於代碼未執行,因此我假設我的if語句出了點問題,也許我未使用'or'運算符||
正確嗎? 任何幫助表示贊賞。
如果要檢查文本框,則需要從文本框中獲取文本。
if (string.IsNullOrWhiteSpace(txtName.Text) || ...
作為一點好處,您也可以這樣寫:
if(new [] {txtName, txtID, txtSalary, txtERR}
.Any(tb => string.IsNullOrWhiteSpace(tb.Text)))
{
MessageBox.Show("One or more text fields are empty or hold invalid data, please correct this to continue","Data Error",MessageBoxButtons.OK);
return;
}
您應該使用TextBox
Text
屬性。 ToString
方法返回字符串“ System.Windows.Forms.TextBoxBase”。 該字符串顯然絕不能為空或為null。
if (string.IsNullOrWhiteSpace(txtName.Text) ||
string.IsNullOrWhiteSpace(txtID.Text) ||
string.IsNullOrWhiteSpace(txtSalary.Text) ||
string.IsNullOrWhiteSpace(txtERR.Text))
{
MessageBox.Show("One or more text fields are empty or hold invalid data, please correct this to continue","Data Error",MessageBoxButtons.OK);
return;
}
如果控件的txtName,txtID等名稱,則需要引用.Text屬性。 嘗試以下類似代碼段的方法:
if (string.IsNullOrWhiteSpace(txtName.Text) ||
string.IsNullOrWhiteSpace(txtID.Text) ||
string.IsNullOrWhiteSpace(txtSalary.Text) ||
string.IsNullOrWhiteSpace(txtERR.Text))
{
MessageBox.Show("One or more text fields are empty or hold invalid data, please correct this to continue","Data Error",MessageBoxButtons.OK);
return;
}
TextBox.ToString()
將返回TextBox
的類型-因此,它永遠不會是NullOrWhiteSpace
。 您想要的是檢查Text
屬性的內容,如下所示:
if (string.IsNullOrWhiteSpace(txtName.Text ||
string.IsNullOrWhiteSpace(txtID.Text) ||
string.IsNullOrWhiteSpace(txtSalary.Text) ||
string.IsNullOrWhiteSpace(txtERR.Text))
{
MessageBox.Show("One or more text fields are empty or hold invalid data, please correct this to continue","Data Error",MessageBoxButtons.OK);
return;
}
我不使用IsNullOrWhiteSpace進行這種測試,相反,我更喜歡使用IsNullOrEmpty
嘗試這個:
if (string.IsNullOrEmpty(txtName.Text)||...)
{...
或者txtName返回TEXT對象...然后嘗試
if (string.IsNullOrEmpty(txtName.Text.toString())||...)
{...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.