1

有从数据库加载图像并在图片框中显示的代码。问题是如果连续没有图片,它将遇到错误,但是我在数据库中标记为允许空图像列。

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);
    } 
}
4

3 回答 3

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);
       }
 } 

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

暗示

在使用任何一种时,Stream您都应该使用Using语句在使用后处理 Stream。

于 2012-05-04T19:38:42.580 回答
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);
    }
}
于 2012-05-04T19:51:17.997 回答
1

只是检查

if(ds.Tables["Images"].Rows[count - 1]["Image"]!=DbNull.Value)
{
   //you code of execution
}
else
{
    //display default image 
}
于 2012-05-04T19:41:48.830 回答