C# 获取多选列表框的selectedvalues
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10198458/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get selectedvalues of multi-select list box
提问by Mike91
I have got a list box in multi select mode which is data bound with 15 values from a database. I have this code to display the selected values of each item selected in the list box:
我有一个多选模式的列表框,它是与数据库中的 15 个值绑定的数据。我有这个代码来显示在列表框中选择的每个项目的选定值:
foreach (var list in list_box.SelectedItems)
{
MessageBox.Show(list_box.SelectedValue.ToString());
}
Unfortunately, the correct amount of message boxes display but they only display the selected value of the first item in the list that has been selected.
不幸的是,显示了正确数量的消息框,但它们只显示已选择列表中第一项的选定值。
Please can someone help me with this issue? I have been searching the net but I cannot find one example that works correctly!
请问有人可以帮我解决这个问题吗?我一直在网上搜索,但找不到一个可以正常工作的例子!
采纳答案by Mike91
I came back to this issue and solved it by doing this:
我回到这个问题并通过这样做解决了它:
foreach(int blah in multilistbox.SelectedIndices){
MessageBox.Show(blah.ToString());
}
Thanks for your help!
谢谢你的帮助!
回答by mreyeros
You should be pulling the value from your listvariable not from the list_box object.
您应该从列表变量而不是从 list_box 对象中提取值。
回答by David Peden
You're looping the selected items already. Why not just call
您已经在循环所选项目。为什么不直接打电话
MessageBox.Show(list.ToString());
回答by mgnoonan
I think you may have a logic error in your code. You are looping through the SelectedItems, but your MessageBoxis still using the list_boxto display a value. How about this?
我认为您的代码中可能存在逻辑错误。您正在遍历SelectedItems,但您MessageBox仍在使用list_box来显示值。这个怎么样?
foreach (var list in list_box.SelectedItems)
{
MessageBox.Show(list.ToString());
}
回答by Jason
foreach (var list in list_box.SelectedItems)
{
MessageBox.Show(list.ToString());
}
回答by Ascariz
can be done this way.
可以这样做。
Int[] AllselectedIndex=ListBox1.GetSelectedIndices();

