2017-07-20 177 views
0

我需要在某些數據中進行搜索。首先,我的代碼選擇了第29位數字並保留它的4位數字(它在下面的1721中,你可以看到),它比較下面的幾行。我設法搜索第29位4位數字並顯示消息,因爲您可以看到行中是否有搜索到的數字,這很容易。這是我的問題;當我搜索該號碼時,如何使它顯示標籤上的前4位數字,後3位數字,後6位數字,後6位數字(label9,label10,label11,label12)。我試圖currentLine.Substring(1, 4);但它顯示了一個錯誤:C#哈希表搜索

substring is null.

我是否需要,如果部分//搜索一個循環?

例如,假設我們把1723的搜索,它必須顯示1097上label9,它必須顯示003 label10,等

數據:

1096:001:161207:085050:1721:001:F:000:0007  
1096:001:161207:085050:1721:001:F:000:0007   
1099:003:161207:085719:1722:001:F:000:0007  
1099:003:161207:085719:1722:001:F:000:0007  
1097:002:161207:085719:1723:001:F:000:0007  
1097:002:161207:085719:1723:001:F:000:0007  

代碼:

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

    String currentItemIndex = "", currentItemData = "", currentLine = ""; 
    Hashtable hashtable = new Hashtable(); 

    private void button1_Click(object sender, EventArgs e) 
    { 
     //Select File 
     openFileDialog1.ShowDialog(); 
     textBox1.Text = openFileDialog1.FileName; 
     //Select File 

     //Read And Split 
     FileInfo file = new FileInfo(openFileDialog1.FileName.ToString()); 
     StreamReader read = file.OpenText(); 

     currentLine = read.ReadLine(); 
     currentItemIndex = currentLine.Substring(23, 4); 
     currentItemData += currentLine; 
     do 
     { 
      currentLine = read.ReadLine(); 
      if (currentLine == null) 
      { 
       hashtable.Add(currentItemIndex, currentItemData); 
       break; 
      } 

      if (!currentItemIndex.Equals(currentLine.Substring(23, 4))) 
      { 
       hashtable.Add(currentItemIndex, currentItemData); 
       currentItemData = ""; 
       currentItemIndex = currentLine.Substring(23, 4); 
      } 


      currentItemData += currentLine; 
     } while (true); 
    } 


    private void button2_Click(object sender, EventArgs e) 
    { 
     //Search Start 
     string search = textBox2.Text; 
     if (hashtable.ContainsKey(search)) 
     { 
      MessageBox.Show("Found"); 
      label9.Text= 
      label10.Text= 
      label11.Text= 
     } 
     else 
     { 
      MessageBox.Show("NotFound"); } 
      //Search End 
     } 
    } 
} 
+0

除了別的,你有什麼理由使用'Hashtable'而不是'Dictionary <,>'?自2005年以來,非泛型集合已經有些過時了 - 對於新代碼... –

+0

您可能會更好地將字符串拆分爲基於':'的值數組。 – JuanR

+0

其實我不知道如何使用'Dictionary' – Osakawa

回答

0

我發現這裏的解決方案是爲好奇的人們:

 string search = textBox2.Text; 
     if (hashtable.ContainsKey(search)) 

     { 

      this.Size = new Size(324, 260); 


      string value1 = (string)hashtable[search]; 
      label9.Text= value1.Substring(0, 4); 
      label10.Text = value1.Substring(5, 3); 
      label11.Text = value1.Substring(9, 6); 
      label12.Text = value1.Substring(16, 6); 
      label13.Text = value1.Substring(23, 4); 
      MessageBox.Show("Found"); 

     } 
     else 
     { 
      MessageBox.Show("NotFound"); 

     }