Else语句总是被执行

本文关键字:执行 语句 Else | 更新日期: 2023-09-27 18:11:21

由于某些原因,我的Else语句总是被执行,即使if语句是。

string line;
string[] columns = null;
while ((line = sr.ReadLine()) != null)
{
    columns = line.Split(',');
    if (columns.Contains(tboxName.Text))
    {
        rtBoxResults.Text = ((columns[0] + " " + columns[1] + " " + columns[2] + " " + columns[3]));
    }
    else
    {
        MessageBox.Show("No Hotels Found.");
        break;
    }

这是因为它正在搜索文件中的每一行,因为while循环而不是每行都包含tboxName吗?

如果是这样,它如何能够返回列[0]的所有值而不使用while循环?

Else语句总是被执行

如果我理解正确,您希望显示消息框,如果none的行在文件中包含tboxName.Text ?如果是这样,您可以在while循环完成后执行此检查,使用bool来跟踪是否有任何行具有匹配:

        string line;
        string[] columns = null;
        bool foundHotels = false;
        while ((line = sr.ReadLine()) != null)
        {
            columns = line.Split(',');
            if (columns.Contains(tboxName.Text))
            {
                rtBoxResults.Text = ((columns[0] + " " + columns[1] + " " + columns[2] + " " + columns[3]));
               foundHotels = true;
            }
         }
         if(!foundHotels)
         {
             MessageBox.Show("No Hotels Found.");               
         }

试试这样

string[] columns = null;
        var isHotels = false;
        while ((line = sr.ReadLine()) != null)
        {
            columns = line.Split(',');
            if (columns.Contains(tboxName.Text))
            {
                rtBoxResults.Text = ((columns[0] + " " + columns[1] + " " + columns[2] + " " + columns[3]));
                isHotels = true;
            }
        } // while loop ends
        if (!isHotels)
        {
            MessageBox.Show("No Hotels Found.");
            break;
        }