Search code examples
c#winformslistviewpictureboxopenfiledialog

How to correctly format a filepath as a string with an OpenFileDialog?


In my Windows application there is a ListView. Each item in this ListView has some SubItems, one of which is used to store a filepath to an image.

Whenever an item in the ListView is selected, the image in a PictureBox is updated with the following code;

private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
    //check that only one item is selected
    if (listView1.SelectedItems.Count == 1)
    {
        //update the image from the filepath in the SubItem
        pictureBox1.Image = Image.FromFile(listView1.SelectedItems[0].SubItems[1].Text);
    }
}

This all works fine. However, when the PictureBox is clicked, it opens an OpenFileDialog to allow the user to select an image. It then changes the SubItem.Text of the currently selected item in the ListView to the filepath of the image, like so;

private void pictureBox1_Click(object sender, EventArgs e)
{
    //open a file dialog to chose an image and assign to the SubItem of the selected item
    openFileDialog1.ShowDialog();
    openFileDialog1.FileName = "";
    string Chosen_File = "";
    Chosen_File = openFileDialog1.FileName;
    listView1.SelectedItems[0].SubItems[1].Text = Chosen_File;
}

However, when the filepath is assigned to Chosen_File, it is not formatted correctly, meaning that when I select the item I get an ArgumentException.

Why is the filepath not formatted correctly, and how can I make sure it is when assigning it to Chosen_File?


Solution

  • You should change your code to NOT remove the selection from the OpenFileDialog and you also need to handle the user selecting the Cancel button on the dialog

    private void pictureBox1_Click(object sender, EventArgs e)
    {
        // Enter the assignment code only if user presses OK
        if(DialogResult.OK == openFileDialog1.ShowDialog())
        {
            // This is you error
            // openFileDialog1.FileName = "";
            string Chosen_File = openFileDialog1.FileName;
            listView1.SelectedItems[0].SubItems[1].Text = Chosen_File;
        }
    }