How do I get at the listbox item's “key” in c# winforms app?

前端 未结 6 1016
南旧
南旧 2020-12-20 20:49

I am writing a winforms app in which a user selects an item from a listbox and edits some data that forms part of an associated object. The edits are then applied from the o

6条回答
  •  被撕碎了的回忆
    2020-12-20 21:18

    A simple and clean way:

    Add Item (include Key and Value) to ListBox:

    lsbListBoxName.Items.Insert(0, New ListItem("Item 1", 1))
    lsbListBoxName.Items.Insert(0, New ListItem("Item 2", 2))
    ...
    


    Get Item on user selection:

    Private Sub lsbListBoxName_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lsbListBoxName.SelectedIndexChanged
        Console.WriteLine(TryCast(lsbListBoxName.SelectedItem, ListItem).Text)
        Console.WriteLine(TryCast(lsbListBoxName.SelectedItem, ListItem).Value)
    End Sub
    

    the lsbListBoxName is name of ListBox and the code is VB.NET you can use This Online Tool to convent to C#.

提交回复
热议问题