【问题标题】:c# i have two List Boxes and 1 dictionaryc# 我有两个列表框和 1 个字典
【发布时间】:2017-06-15 21:42:14
【问题描述】:

我有两个ListBoxes 和1 个Dictionary,当我从Listbox1 中选择一个键时,值将在ListBox2 中选择

Dictionary<string, string> f_list = new Dictionary<string, string>();
 f_list.Add("First Shift", "Lauren");
 f_list.Add("Second Shift", "Jamey");
 f_list.Add("Third Shift", "Salem");
foreach (var t in f_list)
{
   listBox1.Items.Add(t.Key);
   listBox2.Items.Add(t.Value);
}

foreach (var t in f_list) {

  if (listBox1.selecteditem == t.Key) {

  }
}

【问题讨论】:

  • 如果您想从Listbox1 中选择一个键并在ListBox2 中选择值,那么您应该从Listbox1 中获取键并从ListBox2 中获取值
  • 你能告诉我们你到目前为止的代码吗?
  • 我不知道如何使用 'setselected()' 选择值
  • 您需要提供有关您的 UI 的更多上下文。这是 WinForm 或 WPF 应用程序吗?如果是 WPF,你是在后面的代码中写的还是在 MVVM 后面写的?
  • 我不知道第二个foreach 是干什么用的。您应该使用ListBox1OnSelectedIndexChanged 事件,并在该方法中查找其值,在f_list 中找到相应的字符串,然后将该值分配给ListBox2

标签: c# dictionary


【解决方案1】:

我找到了答案

int index = 0;
foreach (var t in f_list) {
   index = listBox2.FindString(t.Value,-1);
   if (listBox1.SelectedItem.ToString() == t.Key)
   {
     listBox2.SetSelected(index, true);
   }
}

【讨论】:

  • 你总是试图找到每一个值,即使它不是被选中的。
  • 您没有利用Dictionary,即使您找到了该项目,您仍会继续重复该过程。检查我的答案。
【解决方案2】:

让我修复你的代码:

string lb1Value = listBox1.SelectedItem.ToString();
if (f_list.ContainsKey(lb1Value))
{
    int index = listBox2.FindStringExact(f_list[lb1Value]);
    listBox2.SetSelected(index, true);
}

此代码应输入listBox1_OnSelectedIndexChanged()

使用字典的想法是直接访问您需要的元素。只有在查找特定值而不是键时,才应该循环遍历它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-25
    • 1970-01-01
    • 2017-08-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多