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