簡體   English   中英

如何比較兩個文本框,如果兩個都為空,如何在C#中打印消息框

[英]how to compare two text box and if both is empty how to print a message box in c#

我在這里比較兩個文本框,如果都為空,則嘗試打印錯誤消息

         int ina=int.Parse(txttea.Text);
         int inb = int.Parse(txtcoffee.Text);
         int inc=0, ind=0;
         if(this.txttea.Text=="" && this.txtcoffee.Text=="")
          {
            MessageBox.Show("select a item");
            txttea.Focus();
          }

您需要||代替&& 在行中:

if(this.txttea.Text=="" && this.txtcoffee.Text=="")

注意:問題與標題不符。

您的問題是如何驗證TextBox空白還是空白

如果您使用的是.Net 3.5或更高版本,則最好使用String.IsNullOrWhiteSpace Method來解決此問題

 if(string.IsNullOrWhiteSpace(txttea.Text) || 
    string.IsNullOrWhiteSpace(txtcoffee.Text))
          {
            MessageBox.Show("select a item");
            txttea.Focus();
            return;
          }

以下內容應為以下內容,請修改您的問題以匹配以下提供的答案

 int ina=int.Parse(txttea.Text);
 int inb = int.Parse(txtcoffee.Text);
 int inc=0, ind=0;
 if(this.txttea.Text=="" || this.txtcoffee.Text=="")
 {
     MessageBox.Show("select an item");
     txttea.Focus();
 }

int.Parse解析空字符串會給你一個異常。 我的意思是: int.Parse("")導致: Input string was not in a correct format.

要解決該問題,請改用TryParse

int ina;
int inb;
if (int.TryParse(txttea.Text, out ina) && int.TryParse(txtcoffee.Text, out inb))
{
    //Ok, more code here
}
else
{
    //got a wrong format, MessageBox.Show or whatever goes here
}

當然,您也可以分別測試它們:[先是ina,然后是inb,反之亦然]:

int ina;
if (int.TryParse(txttea.Text, out ina))
{
    int inb;
    if (int.TryParse(txtcoffee.Text, out inb))
    {
        //Ok, more code here
    }
    else
    {
        //got a wrong format, MessageBox.Show or whatever goes here
    }
}
else
{
    //got a wrong format, MessageBox.Show or whatever goes here
}

現在,關於比較空字符串,如果您想在兩者均為空時顯示消息:

if(this.txttea.Text == "" && this.txtcoffee.Text == "")
{
    MessageBox.Show("select a item");
    txttea.Focus();
}

另一方面,如果要在“至少一個為空”時顯示消息:

if(this.txttea.Text == "" || this.txtcoffee.Text == "")
{
    MessageBox.Show("select a item");
    txttea.Focus();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM