是否可以使用排序列表填充列表框?C#/WinForms

k7fdbhmy  于 7个月前  发布在  C#
关注(0)|答案(2)|浏览(57)

我目前正在为一个大学项目的刽子手为基础的游戏记分牌。
我被告知要创建一个记分牌,显示每个单词的最低猜测量,使用一个列表框显示单词+最低猜测量,并使用一个排序列表存储这些值。
我能够得到我的最低猜测得分到一个sortedlist,但我现在正在努力找到一种方法,以显示它在列表框。
我尝试使用listbox.DataSource属性来填充它,但是我得到了以下错误以及代码行:

lsbScores.DataSource = scores;

字符串
System.ArgumentException:“Complex DataBinding接受IList或IListSource作为数据源。”
我也想过可能做一个循环,遍历我的sortedlist中的值,但是感觉这是错误的方法,如果这是正确的方法,我该怎么做呢?
我觉得使用sortedlist一般是错误的方法,但这是我被告知要做的,所以我需要。

gijlo24d

gijlo24d1#

如果你定义了一个表单级别的变量,

private SortedList<int, string> scores = new();

字符串
在表单设计器中,选择ListBox,选择Properties,然后选择DisplayMember to Value。
在代码中,对分数使用.ToList。

lsbScores.DataSource = scores.ToList();


显示word+lowest guesses
创建一个类,例如下面的类,其中.ToString将用作ListBox的DisplayMember。

public class Guess
{
    public int Key { get; set; }
    public string Value { get; set; }
    public override string ToString() => $"{Key} - {Value}";
}


用于将数据分配给列表框的模型

lsbScores.DataSource = scores
    .Select(x => new Guess()
    {
        Key = x.Key,
        Value = x.Value
    }).ToList(); ;


获取列表框中的当前项。

if (lsbScores.SelectedItem is not null)
{
    Guess current = (Guess)lsbScores.SelectedItem;
}

cgh8pdjw

cgh8pdjw2#

这个例外说明了你可以尝试做什么:
System.ArgumentException:'Complex DataBinding接受IList或IListSource作为数据源。'
大胆是我的,德米特里)
你可以在Linq的帮助下提供所需类型的集合:

using System.Linq;

...

// You may want to use scores.Keys instead of scores.Values
lsbScores.DataSource = scores.Values.ToList();

字符串

相关问题