2012-06-26 69 views
1

來自服務器的數據需要拆分爲ListBox。以下是我的代碼。來自服務器的數據拆分爲列表框

private void button1_Click_2(object sender, EventArgs e) 
     { 
      //String[] arr = new String[1]; 
      listBox1.Items.Clear(); 

      listBox1.Items.Add("No Of Items=" + _server.Q.NoOfItem.ToString()); 
      for (int i=0; i <= _server.Q.NoOfItem - 1; i++) 
      { 
       listBox1.Items.Add(_server.Q.ElementAtBuffer(i).ToString());    
      } 

      listBox2.Items.Add("No Of Items=" + _server.Q.NoOfItem.ToString()); 
      for (int i = 0; i <= _server.Q.NoOfItem - 1; i++) 
      { 
       String words = _server.Q.ElementAtBuffer(i).ToString();    
       listBox2.Items.Add(words.Split(new char[] { '[' , ']', ' '}));     
      } 

listBox1應顯示從服務器檢索到的所有數據。 listBox2應該顯示已拆分的數據。

這怎麼辦?

+0

是什麼與您當前的代碼發生?和你想要什麼輸出? –

+0

我的輸出:name [asd] id [123] age [12]。它假設打印.. asd在listbox1,123在listbox2,12在listbox3 ..但在我的代碼我把所有的結果在listbox1做檢查。所以,在listbox2假設打印出asd –

回答

0

這應該工作:

private void button1_Click_2(object sender, EventArgs e) 
    { 
     //String[] arr = new String[1]; 
     listBox1.Items.Clear(); 

     listBox1.Items.Add("No Of Items=" + _server.Q.NoOfItem.ToString()); 
     for (int i=0; i <= _server.Q.NoOfItem - 1; i++) 
     { 
      listBox1.Items.Add(_server.Q.ElementAtBuffer(i).ToString());    
     } 

     String words = _server.Q.ElementAtBuffer(i).ToString(); 
     listBox2.Items.Add("No Of Items=" + _server.Q.NoOfItem.ToString()); 
     listBox2.Items.AddRange(words.Split(new char[] { '[' , ']', ' '}));   
    }  
+0

它仍然無法正常工作..因爲它不會做任何拆分..但我嘗試把它放在消息框中。它確實..只是不在列表框中。但我真的需要列表box.please幫助我 –

+0

我嘗試使用靜態數據的代碼.. String words =「qwe rty dfg」;它確實有用。但然後什麼時候分開服務器,它不 –

+0

你能給我一個你的服務器的數據看起來像什麼樣子的例子嗎?如果字符串中有'[',']'或/和''字符,它只會被分割。 – davenewza

-1
string[] strArray = words.Split(new char[] { '[' , ']', ' '}) 
for(int x = 0; x < strArray.Count; x++) 
{listBox2.Items.Add(strArray[x]} 

我猜你要分割的話,並添加listboxs 2

+0

我以前用過這個,但它不會工作..當我嘗試把它放在消息框..它,只是它不在列表框。 –

+0

不妨使用AddRange(strArray)。 – davenewza

0
listBox1.Items.Clear(); 

    listBox1.Items.Add("No Of Items=" + _server.Q.NoOfItem.ToString()); 
    listBox2.Items.Add("No Of Items=" + _server.Q.NoOfItem.ToString()); 

    for (int i = 0; i <= _server.Q.NoOfItem - 1; i++) 
    { 
     listBox1.Items.Add(_server.Q.ElementAtBuffer(i).ToString()); 

     String words = _server.Q.ElementAtBuffer(i).ToString(); 
     string[] arr = words.Split(new char[] { '[', ']', ' ' }); 
     foreach (string word in arr) 
      listBox2.Items.Add(word); 
    } 
0

有你嘗試過使用正則表達式:

var pattern = @"\[(.*?)\]"; 
var matches = Regex.Matches(words, pattern); 
foreach (Match m in matches) 
{ 
    listBox2.Items.Add(/* Add matched item */); 
}