gpt4 book ai didi

c# - 遍历列表框中的项目

转载 作者:行者123 更新时间:2023-11-30 22:09:08 25 4
gpt4 key购买 nike

我有一个列表框 (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);
}

sortedListBoxDisplayedMember是“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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com