2013-03-01 56 views
0

我有一個列表框。每當我從數據庫中搜索某個人時,結果都將顯示在列表框中。然後我想要的是每當我從列表框中點擊人物的名字時,人物細節就會顯示在文本框中。我有我的代碼,但問題是隻有我第一次點擊的人的詳細信息顯示在文本框中。在文本框中顯示詳細信息

private void listBox1_SelectedIndexChanged(object sender, EventArgs e) 
    { 
     connection.Open(); 
     OleDbCommand select = new OleDbCommand(); 
     select.Connection = connection; 
     select.CommandText = "Select * From Accounts"; 
     OleDbDataReader reader = select.ExecuteReader(); 

     while (reader.Read()) 
     { 
      if (reader[0].ToString() == listBox1.Tag.ToString()) 
      { 
       fnametb.Text = reader[1].ToString(); 
       lnametb.Text = reader[2].ToString(); 
       agetb.Text = reader[3].ToString(); 
       addresstb.Text = reader[4].ToString(); 
       coursetb.Text = reader[5].ToString(); 
      } 

     } 
     connection.Close(); 

    } 
+0

你引用'listBox1.Tag.ToString()',而不是選擇列表框項目。 – 2013-03-01 07:16:14

+0

是'listBox1.Tag.ToString()'和'listBox1.selectedItem.ToString()'是一樣的嗎? – Pyromancer 2013-03-01 07:17:03

+0

將其更改爲'listBox1.selectedItem.ToString()' – Pyromancer 2013-03-01 07:17:20

回答

0

如果你想用你的代碼,你需要刷新listBox1.Tag並放入Tag選定的列表框項目鍵。或者您需要使用類似於reader[0].ToString() ==listBox1.SelectedValue

0

檢查

if (reader[0].ToString() == listBox1.Tag.ToString()) 
it will not work.... 

你需要一個列表框

0

改變它的選擇指標得到listBox1.selectedItem.ToString()

-1

您的選擇查詢必須具有某些參數,如WHERE子句,以便程序知道數據庫中將加載哪些特定數據。

告訴我什麼是你的列表框中的顯示?

這只是另一種選擇。

0

您正在檢查ListBox.Tag而不是ListBox.SelectedItem

Tag屬性可用於存儲任何要與某個項目關聯的對象。儘管可以存儲任何項目,但標籤屬性通常用於存儲有關項目的字符串信息,例如唯一標識符或項目數據在數據庫中的索引位置。

你可以簡單地檢查SelectedItem,因爲你是在listBox1_SelectedIndexChanged事件反正。

而不是

if (reader[0].ToString() == listBox1.Tag.ToString()) 

嘗試

if (reader[0].ToString() == listBox1.SelectedItem.ToString())