2011-06-02 19 views
0

在C#.Net中,我試圖從選定的ListBox中檢索數據。如何從選定的ListBox中檢索數據?

例如,首先,我在ListBox中顯示了很多從MSSQL 2008數據庫檢索到的數據。 當我從該列表框中選擇單個數據時,我想將選定的數據顯示到文本框中... 我該怎麼做? 我需要你的答案,因爲我只是初學者, 請回答我,如果你知道.. 感謝

回答

2

陷阱的ListBoxSelectedIndexChanged事件,例如,你可以做,

private void listBox1_SelectedIndexChanged(object sender, System.EventArgs e) 
{ 
    textBox1.Text = listBox1.SelectedItem.ToString(); //let textBox1 be your TextBox name and listBox1 be your ListBox name 
} 
+0

感謝答案...我也想知道選擇哪個事件ListBox..SelectedIndexChanged(或)SelectedValueChanged .... 什麼是兩者之間的不同? – Zoro 2011-06-02 05:05:53

+0

感謝您的回答...我也想知道哪個事件選擇ListBox..SelectedIndexChanged(或)SelectedValueChanged .... 這兩者之間有什麼不同? 請回答我.....再次感謝 – Zoro 2011-06-02 05:06:08

+0

是的..你的回答正確...但是當我從列表框中選擇數據並在文本框中顯示該數據時,只顯示「System.Data.DataRowView」字...數據不顯示.... – Zoro 2011-06-02 05:11:04

1

在ASP.NET使用以下代碼:

var selectedValue = listBoxObj.SelectedItem.value; 
2

這實際上取決於您如何將數據存儲到列表中。是簡單的字符串還是一些複雜的對象,無論是哪種情況下,您都可以將選定的項目轉換爲適當的類型。例如, 。 如果你的列表框只包含字符串類型的項目,你會被

string value=(string) this.listBox1.SelectedItem; 

獲得所選擇的項目。如果您的列表框包含其他複雜的類型,你會被

SomeComplexObject value=(SomeComplexObject) this.listBox1.SelectedItem; 

或者,如果你選擇的項目已將列表框綁定到某種數據表或數據集。 您可以使用

string value=listBox1.SelectedValue.ToString(); 

所以,現在, 當列表框中選擇指數變化獲得所選項目的價值。你可以使用設置文本框的值。 首先,訂閱列表框索引更改事件

this.listBox1.SelectedIndexChanged+=new EventHandler(changed); 

而你的處理程序。

private void changed(object sender,EventArgs args) 
     { 
      //set your text box text property here 
      //with the code provided earlier 
     }