【问题标题】:How to correctly format a filepath as a string with an OpenFileDialog?如何使用 OpenFileDialog 将文件路径正确格式化为字符串?
【发布时间】:2016-08-21 15:57:09
【问题描述】:

在我的 Windows 应用程序中有一个 ListView。此 ListView 中的每个项目都有一些 SubItems,其中一个用于存储图像的文件路径。

每当 ListView 中的某个项目被选中时,PictureBox 中的图像都会使用以下代码进行更新;

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);
    }
}

这一切都很好。但是,当单击 PictureBox 时,它会打开一个 OpenFileDialog 以允许用户选择图像。然后将 ListView 中当前选中项的 SubItem.Text 更改为图片的文件路径,如下所示;

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;
}

但是,当文件路径分配给 Chosen_File 时,它​​的格式不正确,这意味着当我选择该项目时,我得到了 ArgumentException。

为什么文件路径的格式不正确,在将其分配给 Chosen_File 时如何确保它是正确的?

【问题讨论】:

  • 也许如果您删除取消 OpenFileDIalog 选择的行 (IE openFileDialog1.FileName = "") 那么您的代码将按预期工作
  • 你也不需要通过临时变量listView1.SelectedItems[0].SubItems[1].Text = openFileDialog1.FileName;
  • @Plutonix 我会解决的。

标签: c# winforms listview picturebox openfiledialog


【解决方案1】:

您应该更改代码以不从 OpenFileDialog 中删除选择,并且您还需要处理用户选择对话框上的取消按钮

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;
    }
}

【讨论】:

  • 完美运行。另外,感谢您提醒我处理用户取消,否则我可能永远不会解决这个问题。
猜你喜欢
  • 1970-01-01
  • 2014-10-12
  • 2015-01-21
  • 2017-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多