【问题标题】:How to add data in ListBox?如何在 ListBox 中添加数据?
【发布时间】:2018-02-02 21:46:01
【问题描述】:

我有字典:

 public Dictionary<int, string> jobs = new Dictionary<int, string>();

它是这样填充的:

 this.jobs.Add(1, "Усі види підземних робіт, відкриті гірничі роботи.");

我尝试从工作字典中添加值:

foreach (KeyValuePair<int, string> kvp in jobs.get()) {
   listBox1.Items.Add(String.Format("№{0} - ({1})", kvp.Key, kvp.Value.ToString()));
}

如您所见,我添加到列表值"№{0} - ({1})"。但是怎么设置key呢?

【问题讨论】:

  • 你是什么意思'如何设置密钥?'
  • 我的意思是为 ListBox 中的项目设置键/值,点击后获取键
  • 什么是jobs.get字典没有这种方法
  • 另一种方法,创建一个包含 key (可能还有 value )和 ToString 方法的 cusotm 对象。将该对象添加到列表框

标签: c# c#-4.0


【解决方案1】:

以下是pm100 建议的示例:

创建一个模型类来绑定列表框,如下:

class Job
  {
        public int Key { get; set; }

        public string Description { get; set; }

        public override string ToString()
        {
            return String.Format("№{0} - ({1})", this.Key, this.Description);
        }
  }

接下来,从字典中投影Job的列表如下:

var jobList = this.jobs
                  .Select(it =>
                                new Job
                                {
                                    Key = it.Key,
                                    Description = it.Value
                                })
                  .ToList();

不要在for-each循环中添加字典项,而是将ListBox的数据源绑定如下:

this.listBox1.DataSource = jobList;

就是这样。列表框将通过调用 Job 类中重写的 ToString() 方法来显示每个项目。

现在您可以通过转换 SelectedItem / SelectedItems 来访问作业对象及其密钥,如下所示:

var job = this.listBox1.SelectedItem as Job;
// job.Key

【讨论】:

    猜你喜欢
    • 2021-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-14
    • 2018-06-06
    • 1970-01-01
    相关资源
    最近更新 更多