在文本文件中搜索一行并显示结果

时间:2017-10-11 00:09:39

标签: c# textbox

我正在尝试为我的迷你项目创建一个搜索框,它应该工作的方式是您输入某个名称并在文本文件中搜索该单词,如果没有找到结果它会显示No results

文本文件包含:

  

Example1 0

     

Example2 1

     

Example2 2

     

Example4 3

     

Example5 4

我希望能够搜索名称,并显示找到的姓名和年龄。

在单击按钮的文本框中:Example5< ---(我正在搜索的内容)

一些伪代码:

private void DynamicButton_Click(object sender, EventArgs e)
{
    Text = this.dynamicTextBox.Text;
    // This is how I want it to work:
    // search names.txt for Text 
    // Get the entire line it was found on
    if (found) {
        MessageBox.Show(result);
    }
    else
    {
        MessageBox.Show("No results");
    }
}

最终结果:一个显示Example5 4

的MessageBox

3 个答案:

答案 0 :(得分:0)

尝试这样的事情:

private void DynamicButton_Click(object sender, EventArgs e)
{
    // Assign text local variable
    var searchText = this.dynamicTextBox.Text;

    // Load lines of text file
    var lines = File.ReadAllLines("names.txt");

    string result = null;
    foreach(var line in lines) {
        // Check if the line contains our search text, note this will find the first match not necessarily the best match
        if(line.Contains(searchText)) {
            // Result found, assign result and break out of loop
            result = line;
            break;
        }
    }

    // Display the result, you could do more such as splitting it to get the age and name separately
    MessageBox.Show(result ?? "No results");
}

请注意,要获得此工作答案,您需要导入System.IO

答案 1 :(得分:0)

您可以使用File.ReadLines

private void dynamicButton_Click(object sender, EventArgs e)
{
    string path = "../../text.txt";
    var lines = File.ReadLines(path).ToArray();
    var found = false;
    for (int i = 0; i < lines.Length; i++)
    {
        if (lines[i].Contains(dynamicTextBox.Text))
        {
            label1.Text = i + 1 + "";
            found = true;
        }
    }
    if (!found)
        label1.Text = "Not Found";
}

行动中: enter image description here

答案 2 :(得分:0)

这样做:

string[] lines = File.ReadAllLines("E:\\SAMPLE_FILE\\sample.txt");
            int ctr = 0;
            foreach (var line in lines)
            {
                string text = line.ToString();
                if (text.ToUpper().Contains(textBox1.Text.ToUpper().Trim()) || text.ToUpper() == textBox1.Text.ToUpper().Trim())
                {
                    //MessageBox.Show("Contains found!");
                    ctr += 1;
                }

            }
            if (ctr < 1)
            {
                MessageBox.Show("Record not found.");
            }
            else
            {
                MessageBox.Show("Record found!");
            }

或者您可以使用此Expression来最小化您的代码:

string[] lines = File.ReadAllLines("E:\\SAMPLE_FILE\\sample.txt");         
var tolist = lines.Where(x => (x.ToUpper().Trim() == textBox1.Text.ToUpper().Trim())).FirstOrDefault();
if (tolist != null)
 {
      MessageBox.Show("Record found.");
 }
 else
 {
     MessageBox.Show("Record not found.");
 }