When I get a Bitmap image from SQL Server DB to display it in a PictureBox, I get an exception:
Parameter is not valid error
Here's my code:
public void FillHotMenu(int key, string connection, string logdir)
{
try
{
SqlConnection conn = new SqlConnection(connectionstr);
conn.Open();
SqlCommand cmd = new SqlCommand("Pm_R_GetHotMenus", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@keyid", key);
SqlDataReader read = cmd.ExecuteReader();
flowLayoutPanel1.Controls.Clear();
while (read.Read())
{
byte[] b = (byte[])(read["KeyBitmap"]);
if (b.Length > 1)
{
PictureBox pic = new PictureBox();
pic.Size = new Size(flowLayoutPanel1.Width / 4, flowLayoutPanel1.Height / 4);
string s = read["KeyBitmap"].ToString();
using (MemoryStream ms = new MemoryStream(b))
{
Bitmap image = new Bitmap(ms); // *** I'm getting error here
pic.Image = image;
}
pic.SizeMode = PictureBoxSizeMode.StretchImage;
flowLayoutPanel1.Controls.Add(pic);
}
else if (read["KeyTextValue"].ToString() != "")
{
textvalue = "";
PictureBox pic = new PictureBox();
pic.Size = new Size(flowLayoutPanel1.Width / 4, flowLayoutPanel1.Height / 4);
textvalue = read["KeyTextValue"].ToString();
pic.Paint += new PaintEventHandler(pictureBox1_Paint);
flowLayoutPanel1.Controls.Add(pic);
}
}
conn.Close();
}
catch (Exception ex)
{
string logstr = ex.InnerException == null ? "" : ex.InnerException.Message;
log.append("ERROR:" + ex.Message + "-->" + logstr, logdirectory);
MessageBox.Show(ex.Message);
Environment.Exit(0);
}
}
How can I solve this problem?
Edit:
I've tried this code with no exceptions but nothing is shown in the PictureBox:
var ms = new MemoryStream(b);
ms.Seek(0, SeekOrigin.Begin);
ms.Position = 0;
byte[] imagebytes = ms.ToArray();
Bitmap bitmap = new Bitmap(pic.Width, pic.Height);
bitmap.Save(ms, ImageFormat.Png);
pic.Image = Image.FromStream(ms);
pic.SizeMode = PictureBoxSizeMode.StretchImage;