PDA

View Full Version : سوال: مشکل با نمایش عکس از دیتابیس



amir200h
چهارشنبه 01 خرداد 1392, 14:51 عصر
سلام به همه دوستان. من از کد زیر برای درج عکس در بانکم استفاده میکنم

private void button1_Click(object sender, EventArgs e)
{
MemoryStream ms = new MemoryStream();
pictureBox1.Image.Save(ms, pictureBox1.Image.RawFormat);
byte[] arraypic = ms.GetBuffer();
SqlConnection con = new SqlConnection();
con.ConnectionString = "server=(local);database=savepic;trusted_connection =yes";
SqlCommand com = new SqlCommand();
com.Connection = con;
com.CommandText = "insert into test (id,pic) values (@id,@pic)";
com.Parameters.AddWithValue("@id", textBox1.Text);
com.Parameters.AddWithValue("@pic", arraypic);
con.Open();
com.ExecuteNonQuery();
con.Close();
MessageBox.Show("ok");

}

ولی هنگامی که میخوام عکسو از بانک بخونم با کد زیر، با خطا مواجه میشه


private void button2_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "server=(local);database=savepic;trusted_connection =yes";
SqlCommand com = new SqlCommand();
com.Connection = con;
com.CommandText = "select * from test where id=" + textBox1.Text;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = com;
DataSet ds = new DataSet();
da.Fill(ds);
byte[] arraypic = {Convert.ToByte(ds.Tables[0].Rows[1].ToString())};
MemoryStream ms = new MemoryStream(arraypic);
pictureBox2.Image = Image.FromStream(ms);
}

104524

khokhan
چهارشنبه 01 خرداد 1392, 15:27 عصر
سلام به همه دوستان. من از کد زیر برای درج عکس در بانکم استفاده میکنم







در رویداد کلیک باتن بازیابی تصاویر بایستی یه چیزی شبیه این بنویسین

نام رشته اتصال رو هم خودتون ست کنین :لبخند:


private void button1_Click(object sender, EventArgs e)
{

SqlConnection con = new SqlConnection(connect);
SqlCommand cmd = new SqlCommand();
try
{
con.Open();
cmd.Connection = con;
cmd.CommandText = "select pic from test where id=" + textBox1.Text; // for this example only get top record
byte[] Img = (byte[])cmd.ExecuteScalar();

// Convert the image record to file stream and display it to picture control
string str = Convert.ToString(DateTime.Now.ToFileTime());
FileStream fs = new FileStream(str, FileMode.CreateNew, FileAccess.Write);
fs.Write(Img, 0, Img.Length);
fs.Flush();
fs.Close();
pictureBox1.Image = Image.FromFile(str);
}
catch
{
MessageBox.Show("Error while saving image.", "Error");
}
finally
{
con.Close();
}