2017-10-11 152 views
-1

我想爲我的迷你項目製作一個搜索框,它應該工作的方式是您鍵入某個名稱,然後在文本文件中搜索該單詞,如果沒有找到結果,則顯示No results在文本文件中搜索一行並顯示結果


文本文件包括:

例1 0

例2 1

例2 2

範例4 3

例5 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
+1

如果您需要幫助的代碼,您需要發佈您的代碼。這不是一個代碼寫入服務。請閱讀[問]並參加[旅遊] – Plutonix

回答

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

+0

非常感謝! – Roto

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

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."); 
} 
相關問題