【发布时间】: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