作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个列表框 (sortedListBox
),我用组合框 (allItemsComboBox
) 中的项目填充了它:
int index = sortedListBox.FindString(allItemsComboBox.Text, -1);
if (index == -1)
{
var item=new { Text = allItemsComboBox.Text , Value = allItemsComboBox.Value};
sortedListBox.Items.Add(item);
}
sortedListBox
的DisplayedMember
是“Text”,ValueMember
是“Value”。
现在我想遍历 ListBox 中的所有项目并获取其值:
public static string ListBoxToString(ListBox lb)
{
List<string> values = new List<string>();
for (int i = 0; i < lb.Items.Count; i++)
{
values.Add(lb.Items[i].ToString());
}
string result = String.Join(",", values);
return result;
}
在这一行中:values.Add(lb.Items[i].ToString());
我得到:
{ Text = "Size" , Value = "cte1.Size"}
我只想得到值,即“cte1.Size”
如何遍历 ListBox 中的项目并获取这些项目的 ValueMember
?
最佳答案
我不知道有什么方法可以要求 ListBox
以这种方式为您评估 ValueMember
...并且因为您使用的是匿名类型,变得更难获取值。
选项:
例如:
public static string ListBoxToString(ListBox lb)
{
var values = lb.Items
.Cast<dynamic>()
.Select(x => x.Value.ToString());
return string.Join(",", values);
}
动态类型提供了最即时 的修复,但我强烈建议您考虑使用自定义类型。 (不需要多写几行。)
关于c# - 遍历列表框中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21721255/
我是一名优秀的程序员,十分优秀!