2011-04-03 85 views
4

您好 將選定索引的值從列表框指定給變量的正確方法是什麼?用戶在列表框中選擇一個項目,然後輸出根據他們的選擇而改變。Listbox.selected索引更改變量賦值

我用:

variablename = listbox.text 
listBox_SelectedIndexChanged事件

和工作原理。

當我使用button_click事件中,我使用:

variablename = listbox.selectedindex 

但是,這並不在listbox_selectedindexchanged事件工作。

請讓我知道是否可以像上面那樣使用它,或者我會遇到問題以及爲什麼不能使用selectedindex方法。

謝謝!

回答

4

答:聽起來你的變量是一個字符串,但你試圖給它分配由SelectedIndex屬性返回的值,它是一個整數。

B.如果您嘗試檢索與Listbox的SelectedINdex關聯的項目的值,請使用Index返回Object本身(列表框是對象的列表,這些對象通常但並非總是如此)將成爲字符串)。

Private Sub ListBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged 
    'THIS retrieves the Object referenced by the SelectedIndex Property (Note that you can populate 
    'the list with types other than String, so it is not a guarantee that you will get a string 
    'return when using someone else's code!): 
    SelectedName = ListBox1.Items(ListBox1.SelectedIndex).ToString 
    MsgBox(SelectedName) 
End Sub 

這是一個小更直接,使用SelectedItem屬性:

Private Sub ListBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged 

    'This returns the SelectedItem more directly, by using the SelectedItem Property 
    'in the event handler for SelectedIndexChanged: 
    SelectedName = ListBox1.SelectedItem.ToString 
    MsgBox(SelectedName) 

End Sub 
2

那麼這取決於你想從列表框中選擇的項目。

有幾種可能的方式,讓我試着解釋一些這些作業。

假設你有兩列,他們行的數據表...

ID Title 
_________________________ 
1  First item's title 
2  Second item's title 
3  Third item's title 

你這個數據表綁定到你的列表框,

ListBox1.DisplayMember = "ID"; 
ListBox1.ValueMember = "Title"; 

如果用戶選擇第二項目從列表框中。

現在,如果你想獲得所選項目的顯示值(標題),那麼你可以做

string displayValue = ListBox1.Text; // displayValue = Second item's title 

,甚至這得到相同的結果。

// displayValue = Second item's title 
string displayValue = ListBox1.SelectedItem.ToString(); 

而得到的數值成員對選定的項目,你需要做的

string selectedValue = ListBox1.SelectedValue; // selectedValue = 2 

現在有情況下,當你希望允許用戶從列表框中選擇一個以上的項目,所以你再設置

ListBox1.SelectionMode = SelectionMode.MultiSimple; 

OR

ListBox1.SelectionMode = SelectionMode.MultiExtended; 

現在假設用戶選擇兩個項目;第二和第三。

所以,你可以通過簡單地通過SelectedItems

string displayValues = string.Empty; 
foreach (object selection in ListBox1.SelectedItems) 
{ 
    displayValues += selection.ToString() + ","; 
} 

// so displayValues = Second item's title, Third item's title, 

迭代得到顯示值,如果你想獲得ID's代替Title's然後...

我也找過它,我將發佈,如果找到。

我希望你的理解能夠建立。

祝你好運!