2017-05-25 29 views
-2

我試圖創建一個在列表框中搜索名稱的應用程序。 基本上,我有2個.txt文件(BoyNames,GirlNames),一個文件包含一組男孩的名字和其他女孩的名字。我設法將boyNameListBox和女孩名稱顯示給girlNameListBox。請參閱附件中的圖像。我試圖添加一個函數,如果用戶輸入一個男孩的名字(在男孩文本框中)並且名字在列表框中被列出,那麼該應用將返回一個顯示「流行」的消息框;如果名稱未列出,該應用程序將顯示一個顯示不受歡迎的消息框。我希望包括相同的搜索功能,但女孩的名字。我對編程非常陌生,並且非常感謝您的幫助。提前致謝!!不能弄清楚如何在列表框中搜索項並返回結果

public partial class Form1 : Form 
{ 
    public Form1() 
    { 
     InitializeComponent(); 
    } 

    private void readButton_Click(object sender, EventArgs e) 
    { 
     { 
      //local variables 
      string line1; 

      //Catch Boy Names File 
      System.IO.StreamReader file = new System.IO.StreamReader(@"C:\Users\Harra\Documents\Visual Studio 2017\Projects\Name Search\BoyNames.txt"); 

      //display items BoyNames file to Listbox 
      while ((line1 = file.ReadLine()) != null) 
       boyNameListbox.Items.Add(line1); 
     } 

     { 
      //local variales 
      string line2; 

      //Catch Girl Names File 
      System.IO.StreamReader file = new System.IO.StreamReader(@"C:\Users\Harra\Documents\Visual Studio 2017\Projects\Name Search\GirlNames.txt"); 

      //display items GirlNames file to Listbox 
      while ((line2 = file.ReadLine()) != null) 
       girlNameListbox.Items.Add(line2); 
     } 


    } 

    private void boyButton_Click(object sender, EventArgs e) 
    { 

    } 

    private void girlButton_Click(object sender, EventArgs e) 
    { 

    } 
} 

enter image description here

+0

做一個簡單的谷歌搜索..也編輯你的代碼並正確格式化你有'{}'使用不當..這並不困難 – MethodMan

+0

感謝您的迴應,是的ive試圖谷歌搜索,但由於我有限的水平我無法理解的技能。你能幫忙嗎? – Relaxsingh

+0

需要時間去谷歌一些'C#基礎知識初學者教程'是我會開始..大量免費的在線資源/教程/視頻 – MethodMan

回答

0

喜歡的東西:

private void boyButton_Click(object sender, EventArgs e) 
{ 
    string boyname = boyTextBox.Text; 
    bool found = false; 
    for(int n = 0; n < boyNameListbox.Items.Count; n++) 
    { 
     if (boyNameListbox.Items[n] == boyname) 
     { 
      found = true; 
      break; 
     } 
    } 

    if (found) 
     MessageBox.Show("popular"); 
    else 
     MessageBox.Show("not popular"); 

} 

你要知道,我沒有整個代碼的形式,所以也許小錯誤,但希望你從這個例子中的想法。希望這足以讓你開始併成爲被接受的答案。

+0

嗨,我真的很感謝你的迴應!我在(找到)處得到紅色波浪線。繼承人錯誤消息:「使用未分配的本地變量」找到'。「。 – Relaxsingh

+0

只是做了一個編輯,應該改正這一點。如果它能幫助你,我會很樂意接受我的答案。 ;) – TomServo

+0

嗨,太棒了!有用。我得到了另一個錯誤,但現在用綠色波浪線:(boyNameListbox.Items [n] == boyname)。解決此問題後,我相信該應用應該可以正常工作。下面是錯誤消息:「可能的意外引用比較,爲了獲得值比較,將左邊的字符串轉換爲」string「。」再次感謝! – Relaxsingh