namespace dota2
{
public partial class Form1 : Form
{
private SqlConnection cn = new SqlConnection();
private SqlCommand cmd = new SqlCommand();
private SqlDataReader dr;
private SqlParameter picture;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection(global::dota2.Properties.Settings.Default.Database1ConnectionString);
cmd.Connection = cn;
picture = new SqlParameter("@picture", SqlDbType.Image);
}
private void button1_Click(object sender, EventArgs e)
{
open();
}
private void button2_Click(object sender, EventArgs e)
{
savepicture();
}
private void savepicture()
{
if (pictureBox1.Image != null)
{
MemoryStream ms = new MemoryStream();
pictureBox1.Image.Save(ms, pictureBox1.Image.RawFormat);
byte[] a = ms.GetBuffer();
ms.Close();
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("@picture", a);
cmd.CommandText = "insert into pictures (name,picture) values ('" + textBox1.Text.ToString() + "',@picture)";
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
textBox1.Text = "";
pictureBox1.Image = null;
MessageBox.Show("Image Saved", "Programming At Kstark");
}
}
private void open()
{
try
{
OpenFileDialog f = new OpenFileDialog();
f.InitialDirectory = "C:/Picture/";
f.Filter = "All Files|*.*|JPEGs|*.jpg|Bitmaps|*.bmp|GIFs|*.gif";
f.FilterIndex = 0;
if (f.ShowDialog() == DialogResult.OK)
{
pictureBox1.Image = Image.FromFile(f.FileName);
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
pictureBox1.BorderStyle = BorderStyle.Fixed3D;
textBox1.Text = f.SafeFileName.ToString();
}
}
catch { }
}
}
}
我的表单有一个图片框以及Open
和Save
按钮。我试图使用下面的代码将图片从我的图片框插入数据库。图片按原样打开并显示在图片框中,但按下保存按钮不起作用。它说要么cn。打开是一个错误或执行查询。