在我的Windows應用程序中有一個ListView。此ListView中的每個項目都有一些子項目,其中一個用於將文件路徑存儲到圖像。如何使用OpenFileDialog將文件路徑正確地格式化爲字符串?
每當選中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。
爲什麼filepath格式不正確,我怎樣才能確保將它分配給Chosen_File?
按鈕( IE瀏覽器openFileDialog1.FileName =「」),那麼你的代碼將按預期工作 – Steve
你也不需要通過一個temp var listView1.SelectedItems [0] .SubItems [1] .Text = openFileDialog1.FileName; – Plutonix
@Plutonix我會解決這個問題。 –