首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何将listBox只添加到dictionary<string的左侧,string>?

如何将listBox只添加到dictionary<string的左侧,string>?
EN

Stack Overflow用户
提问于 2022-10-14 04:53:19
回答 2查看 48关注 0票数 1

在表格的顶部

代码语言:javascript
运行
复制
Dictionary<string, string> FileList = new Dictionary<string, string>();

在构造函数中

代码语言:javascript
运行
复制
public Form1()
{
    InitializeComponent();
      
    if (System.IO.File.Exists(Path.Combine(path, "test.txt")))
    {
        string g = System.IO.File.ReadAllText(Path.Combine(path, "test.txt"));
        FileList = JsonConvert.DeserializeObject<Dictionary<string, string>>(g);
        listBox1.DataSource = FileList.ToList();
    }

取而代之的是:

代码语言:javascript
运行
复制
listBox1.DataSource = FileList.ToList();

然后我将在listBox中看到例如"hello“、"d:\test\test1.txt”

我希望在listBox中只有:“你好”

我不想更改FileList,而是要更改将从FileList添加到listBox的内容,这只是左侧。

另一个问题可能是listBox所选索引的问题:

代码语言:javascript
运行
复制
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    var item = ((ListBox)sender).SelectedItem;
    var itemCast = (KeyValuePair<string, string>)item;
    pictureBox1.Image = System.Drawing.Image.FromFile(itemCast.Value);
}

一方面,我不希望在listBox中看到右侧的值,另一方面,我希望所选的索引事件能够正常工作。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-10-14 05:01:39

字典将键映射到值。您所称的“左部分/侧”实际上是关键,而另一个元素是值。

C# Dictionary有一个属性:Keys,它只返回字典中的(例如,"hello"字符串)。

因此,您可以使用:

代码语言:javascript
运行
复制
listBox1.DataSource = FileList.Keys.ToList();

注意,如果您只需要(例如"d:\test\test1.txt"等),那么Dictionary具有类似的属性:。

票数 2
EN

Stack Overflow用户

发布于 2022-10-14 05:11:24

我猜,当用户选择一个键时,您会希望得到相应的值。在这种情况下,不只是绑定键,而是绑定整个Dictionary

代码语言:javascript
运行
复制
myListBox.DisplayMember = "Key"
myListBox.ValueMember = "Value"
myListBox.DataSource = myDictionary.ToArray()

每个项目都是一个KeyValuePair,它具有KeyValue属性。上面的代码将显示键,然后,当用户选择一个项时,您可以从SelectedValue属性中获得相应的值。

注意,这样的数据绑定需要一个IList,而Dictionary只实现ICollection。因此,您需要调用ToArrayToList来创建用于绑定的IList

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74064447

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档