您的位置:宽带测速网 > 编程知识 > ListBox中怎么获取用户选定的值

ListBox中怎么获取用户选定的值

2025-06-17 15:28来源:互联网 [ ]

要获取用户在ListBox中选定的值,可以通过SelectedIndex属性来获取选定项的索引,并通过Items集合来获取选定项的值。示例代码如下:

// 获取ListBox中选定项的索引int selectedIndex = listBox1.SelectedIndex;// 获取选定项的值string selectedValue = listBox1.Items[selectedIndex].ToString();// 输出选定项的值Console.WriteLine(selectedValue);

在上面的代码中,假设listBox1是一个ListBox控件,通过SelectedIndex属性获取用户选定项的索引,然后通过Items集合获取该索引对应的项的值,最后输出选定项的值。