选择列表框的项目,它匹配字符串数组的项目 [英] to make items of a listbox selected, which matches items of a string array

查看:76
本文介绍了选择列表框的项目,它匹配字符串数组的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是wpf的新手。我想将列表框中的项目(与字符串数组中的项目匹配)设置为选中(使用c#编码)。我在这里给出了我的代码:

Hi, I''m new to wpf. I want to make the items in a listbox, which matches items in a string array, as selected (using c# coding). I''m giving my code here:

string str1 = myReader["Books"].ToString();
                string[] arr = str1.Split(',');
                foreach (string word in arr)
                {
                   foreach (ListBoxItem x in listBox1.Items)
                        {
                            if (x.Content.ToString() == word)
                            {
                                listBox1.SelectedItems.Add(x);
                            }
                        }
                }





字符串str1的内容是''Book1,Book2, Book3,Book4''。

但问题是,我必须使用单个foreach循环来完成它。即,我必须将行''foreach(ListBoxItem x in listBox1.Items)'更改为某些if条件。

任何人都可以帮助我???



The content of string str1 is ''Book1,Book2,Book3,Book4''.
But the problem is, I''ve to do it using a single foreach loop. ie., I''ve to change the line ''foreach (ListBoxItem x in listBox1.Items)'' as some if condition.
Can anyone help me???

推荐答案

查看此修改后的代码。



Check this modified code.

string str1 = myReader["Books"].ToString();
string[] arr = str1.Split(',');
foreach (string word in arr)
{
  int index = listbox1.FindString(word)
  if (index != -1 )
  {
     listBox1.SelectedItems.Add(word);
  }
 
  }
};





了解更多关于ListBox.FindString @的信息 MSDN [ ^ ]


这篇关于选择列表框的项目,它匹配字符串数组的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆