I am new to C#
I just want to ask if is it possible to check against a SUBItem in a listview for repeated values before i do a ADD()
method??
Lets say i have a listview and i can add/delete items
I can have numerous items and subitems
I would like to perform a check before adding the file that i'm opening into the listview
The file that I'm going to put into would be, name of a file, eg example.txt
And if this file exists in the subitem, i will not add into the listview
Does anyone have any idea on how to check a subitem value against the value that I'm goi开发者_StackOverflow中文版ng to add into?
TIA
Well, you can iterate through the Items property of the ListView, and then the Subitems property for each item and finally check against the subitem's Text property.
The other option is to store the already added items in a List, and check if it already contains that item you want to add.
Edit: as requested, added sample code below.
private bool _CheckFileName(string fileName)
{
foreach(ListViewItem item in this.myListView.Items)
{
// this is the code when all your subitems are file names - if an item contains only one subitem which is a filename,
// then you can just against that subitem, which is better in terms of performance
foreach(ListViewItem.ListViewSubItem subItem in item.SubItems)
{
// you might want to ignore the letter case
if(String.Equals(fileName, subItem.Text))
{
return false;
}
}
}
return true;
}
using(var ofd = new OpenFileDialog())
{
// ... setup the dialog ...
if(ofd.ShowDialog() == DialogResult.Cancel)
{
// cancel
return;
}
// note that FileOpenDialog.FileName will give you the absolute path of the file; if you want only the file name, you should use Path.GetFileName()
if(!_CheckFileName(ofd.FileName))
{
// file already added
return;
}
// we're cool...
}
I didn't test the code so it is possible that I have some typos, if so, please add a comment and I'll fix it (though perhaps it would be better if you tried to figure it out yourself first :)).
You could create a helper class that contains information about each item. For each ListViewItem
you create a new instance of this class and set ListViewItem.Tag
to this instance.
You'd only have to iterate over all the items, get the helper object for the item and compare with that helper object.
精彩评论