从图像列可能为空的数据库加载图片框图像

时间:2012-05-04 19:36:28

标签: c# sql-server

有从数据库加载图像的代码,并在图片框中显示。问题是如果连续没有pic会遇到错误,但我在数据库中标记为allow nulls image列。

private void button1_Click(object sender, EventArgs e)
{
    sql = new SqlConnection(@"Data Source=PC-PC\PC;Initial Catalog=Test;Integrated Security=True");
    cmd = new SqlCommand();
    cmd.Connection = sql;
    cmd.CommandText = ("select Image from Entry where EntryID =@EntryID");
    cmd.Parameters.AddWithValue("@EntryID", Convert.ToInt32(textBox1.Text));
    var da = new SqlDataAdapter(cmd);
    var ds = new DataSet();
    da.Fill(ds, "Images");
    int count = ds.Tables["Images"].Rows.Count;

    if (count > 0)
    { 
    var data = (Byte[])(ds.Tables["Images"].Rows[count - 1]["Image"]);
    var stream = new MemoryStream(data);
    pictureBox1.Image= Image.FromStream(sream);
    } 
}

3 个答案:

答案 0 :(得分:4)

您应该检查DbNull.Value

这应该可以解决问题:

if (count > 0)
{ 
       if (ds.Tables["Images"].Rows[count - 1]["Image"] != DbNull.Value){
          var data = (Byte[])(ds.Tables["Images"].Rows[count - 1]["Image"]);
          (MemoryStreamstream = new MemoryStream(data)
           pictureBox1.Image= Image.FromStream(sream);
       }
 } 

您将列标识DB标记为接受空值,以便DB处理它,但您还需要在应用程序中处理null(不能转换DbNull值)。

<强>提示

在使用任何类型的Stream时,您应该使用Using语句在使用后处理Stream。

答案 1 :(得分:2)

仅供参考,您需要学习使用using块。即使抛出异常,这也将确保对象及时处置:

private void button1_Click(object sender, EventArgs e)
{
    var ds = new DataSet();
    using (
        var sql =
            new SqlConnection(
                @"Data Source=PC-PC\PC;Initial Catalog=Test;Integrated Security=True")
        )
    {
        using (
            var cmd = new SqlCommand
                          {
                              Connection = sql,
                              CommandText =
                                  "select Image from Entry where EntryID = @EntryID"
                          })
        {
            cmd.Parameters.AddWithValue(
                "@EntryID",
                Convert.ToInt32(textBox1.Text));
            using (var da = new SqlDataAdapter(cmd))
            {
                da.Fill(ds, "Images");
            }
        }
    }

    var imagesTable = ds.Tables["Images"];
    var imagesRows = imagesTable.Rows;
    var count = imagesRows.Count;

    if (count <= 0)
        return;
    var imageColumnValue =
        imagesRows[count - 1]["Image"];
    if (imageColumnValue == DBNull.Value)
        return;

    var data = (Byte[]) imageColumnValue;
    using (var stream = new MemoryStream(data))
    {
        pictureBox1.Image = Image.FromStream(stream);
    }
}

答案 2 :(得分:1)

只需检查

if(ds.Tables["Images"].Rows[count - 1]["Image"]!=DbNull.Value)
{
   //you code of execution
}
else
{
    //display default image 
}