c#在datagridview

时间:2017-08-26 10:33:29

标签: c# datagridview

我正在尝试将图像插入到sql server中,然后我想在c#中的datagridview中渲染回来。我从互联网上获取了这些代码。我遵循数据库方案

create table product
 (
   product_id int not null primary key identity,
   product_serialno varchar(10) not null unique,
   product_name varchar(60) not null,
   brand_id int,
   category_id int,
   img varbinary,
   remarks text
  )

我已使用以下代码进行插入

MemoryStream ms = new MemoryStream();
Picture.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] pic_arr = new byte[ms.Length];

SqlConnection con = new SqlConnection(ConfigurationSettings.AppSettings["conSetting"]);
 String sql = "Insert into product(product_serialno,product_name,brand_id,category_id,img,remarks) values(@product_serialno,@product_name,@brand_id,@category_id,@img,@remarks)";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("@product_serialno",txtProductSerial.Text);
cmd.Parameters.AddWithValue("@product_name",txtProductName.Text);
cmd.Parameters.AddWithValue("@brand_id",txtbrand.Text);
cmd.Parameters.AddWithValue("@category_id",txtcategory.Text);
cmd.Parameters.AddWithValue("@img",pic_arr);
cmd.Parameters.AddWithValue("@remarks",txtRemarks.Text);

try
{
    con.Open();
    int i = cmd.ExecuteNonQuery();
}catch (Exception ex)
{
    MessageBox.Show("Enter all required field", "Error !!");
}finally
{
    con.Close();
    reset();
}

现在我尝试使用以下代码

在datagridview中显示它
SqlConnection con = new SqlConnection(ConfigurationSettings.AppSettings["conSetting"]);
String sql = "Select * From product";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader dataReader;

try
{
    con.Open();
    dataReader = cmd.ExecuteReader();
    try
    {
       while (dataReader.Read())
       {
           byte[] img= (byte[])dataReader.GetValue(5);
           MemoryStream ms = new MemoryStream(img);

           //dataGridView1.
           dataGridView1.Rows.Add(dataReader[0].ToString(), dataReader[1].ToString(), dataReader[2].ToString(), dataReader[3].ToString(), dataReader[4].ToString(), Image.FromStream(ms), dataReader[6].ToString());                    
         }
     }catch(Exception ex)
     {
         MessageBox.Show(ex.ToString(),"Exception");
     }
}catch (Exception ex){  
}finally{
         con.Close();
}

渲染图片时遇到错误。如果有人帮我解决这个问题会很好。

1 个答案:

答案 0 :(得分:1)

将图像写入数据库时​​,您缺少一些步骤

MemoryStream ms = new MemoryStream();
Picture.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);

// Reposition the Memory stream to the beginning of the data
ms.Seek (0, SeekOrigin.Begin);

// Allocate the array
byte[] pic_arr = new byte[ms.Length];

// Read the bytes into the array
ms.Read (pic_arr, 0, ms.Length);

现在,您的数组包含要写入数据库的有效字节。

我还建议您不要使用AddWithValue,而是使用更精确的Add以及参数的特定数据类型。虽然方便的AddWithValue是您的数据库引擎的well known to be source of bugs and underperformances