现在的位置: 首页 > 综合 > 正文

向listBox添加数据时,判断添加的数据是否在listBox中已存在

2013年03月27日 ⁄ 综合 ⁄ 共 372字 ⁄ 字号 评论关闭

今天做到一个功能,使用openFileDialog,选择文件,然后将选择了的文件放入listBox中,想判断如果要添加的数据在LISTBOX中已存在,就不要添加。

想着是用循环遍历,但是感觉很麻烦,网上找了个方法,

直接贴上代码

string str = "";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
for (int i = 0; i < openFileDialog1.FileNames.Length; i++)
{
str
= openFileDialog1.FileNames.GetValue(i).ToString();
//判断是否在LISTBOX集合中存在,不存在就添加,存在就不管
if (!listBox1.Items.Contains(str))
{
listBox1.Items.Add(str);
}


}

}

抱歉!评论已关闭.