質問

I am developing a windows forms application which uses OpenFileDialog to select files and drop it to a ListView.

The user should not be able to add same file to the listview twice. This should NOT happen:

This should NOT happen!!!!

How can this be done??

役に立ちましたか?

解決 2

Try out this code.

if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
    var file = openFileDialog1.FileName;
    if (listView1.FindItemWithText(file) == null)
        listView1.Items.Add(file);
}

You can also add else with a message box informing user about choosing a duplicate file.

他のヒント

Have you tried checking if the listview contains the file before adding a new one?

The openfiledialog lets you filter by extension, but not by file name so you need to process the user selection after it closes. Perhaps showing a message dialog to tell the user that they selected a duplicate would be the best way to handle the invalid selection.

Check against existing entries.

var txt = comboBox1.Text;

if (!listView1.Items.ContainsKey(txt))
{
    lvi.Text = txt;

    // this is the key that ContainsKey uses. you might want to use the value 
    // of the ComboBox or something else, depending the combobox is freetext 
    // or regarding your scenario.
    lvi.Name = txt;

    lvi.SubItems.Add("");
    lvi.SubItems.Add("");
    lvi.SubItems.Add("");
    lvi.SubItems.Add("");

    listView1.Items.Add(lvi);
}

How prevent duplicate items listView C#

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top