如何从c#的任何目录中打开,选择并添加一个表单内的jpeg格式文件?这是代码。
private void open2ToolStripMenuItem_Click(object sender, EventArgs e)
{
pictureBox1.Visible = true;
string Chosen_File = "";
Chosen_File = openFileDialog1.FileName;
openFileDialog1.Title = "Insert an image";
openFileDialog1.InitialDirectory = System.Environment.GetFolderPath(Environment.SpecialFolder.Personal);
openFileDialog1.FileName ="";
openFileDialog1.Filter = "JPEG Images|*.jpg|GIF Images|*.gif|All Files|";
openFileDialog1.ShowDialog();
if (openFileDialog1.ShowDialog() != DialogResult.Cancel)
{
Chosen_File = openFileDialog1.FileName;
pictureBox1.Image = Image.FromFile(Chosen_File);
}
}
答案 0 :(得分:1)
你有一个openFileDialog1.ShowDialog();
到多个。删除第一个,只使用if
子句中的一个!然后if
子句在显示对话框后使用结果。我也更喜欢明确检查DialogResult.OK
,但这不应该有所作为。
您的代码显示对话窗口两次,不是吗? (当然可以!)如果您选择要在第一个对话框上显示的图像,您将再次获得该对话框,然后必须在那里确定。如果取消第二个对话框,则不会显示任何内容。
结果,即用户的选择仅直接从Show()返回;如果你不抓住那里它就会丢失!这与选择的内容,对话框的字段(例如文件名)不同,后面都有。
答案 1 :(得分:1)
首先删除第一个openFileDialog1.ShowDialog()
private void button1_Click(object sender, EventArgs e)
{
pictureBox1.Visible = true;
string Chosen_File = "";
Chosen_File = openFileDialog1.FileName;
openFileDialog1.Title = "Insert an image";
openFileDialog1.InitialDirectory = System.Environment.GetFolderPath(Environment.SpecialFolder.Personal);
openFileDialog1.FileName = "";
openFileDialog1.Filter = "JPEG Images|*.jpg|GIF Images|*.gif|All Files|";
//openFileDialog1.ShowDialog();
if (openFileDialog1.ShowDialog() != DialogResult.Cancel)
{
Chosen_File = openFileDialog1.FileName;
pictureBox1.Image = Image.FromFile(Chosen_File);
}
}
除此之外,您的代码运作良好!