C#,WFA,使用 .NET 4.5 平台,
我删除了 textBox1(名字)、textBox2(姓氏)、pictureBox1(员工照片)、button2(浏览)和 button1(保存)来插入新员工。
button2 -> 必须浏览图片并在pictureBox1中显示,
button1 -> 必须将 button2 浏览并由 pictureBox1 显示的图像保存到 localhost 中的此表中。
运行程序后,出现此错误(找不到文件。)
(虽然我单独浏览没有任何错误)
我只想要包含修复此 WFA 的代码的答案。只是想确定我对此非常清楚。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Data.SqlClient;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
SqlConnection cnn = new SqlConnection("Initial Catalog=randomcompany;Data Source=localhost;Integrated Security=SSPI;");
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e) //Browse button
{
try
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "Images (*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|" + "All files (*.*)|*.*";
dlg.Title = "Select Employee Picture";
if (dlg.ShowDialog() == DialogResult.OK)
{
pictureBox1.Image = System.Drawing.Image.FromFile(dlg.FileName);
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void button1_Click(object sender, EventArgs e) //Save button
{
try
{
cnn.Open();
string path = pictureBox1.Image.ToString();
Byte[] imagedata = File.ReadAllBytes(path);
SqlCommand cmd = new SqlCommand("INSERT INTO Employees (EmployeeFirstname, EmployeeLastname, EmployeePhoto) VALUES (@item1,@item2,@img", cnn);
cmd.Parameters.AddWithValue("@item1", textBox1.Text);
cmd.Parameters.AddWithValue("@item2", textBox2.Text);
cmd.Parameters.AddWithValue("@img", imagedata);
cmd.ExecuteNonQuery();
cnn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}