Reputation: 197
there is the code for loading image from database and shows it in picture box. the problem is if there's no pic in a row it will encounter an error however i marked as allow nulls image column in database.
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);
}
}
Upvotes: 1
Views: 2469
Reputation: 161781
FYI, you need to learn to use using
blocks. This will ensure that the objects are Disposed of in a timely manner, even if an exception is thrown:
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);
}
}
Upvotes: 2
Reputation: 4629
you should check for DbNull.Value
.
This should do the trick:
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);
}
}
You marked column id DB to accept null value so DB handles it but you also need do handle null in your application (you cannot cast DbNull value).
Hint
While using any kind of Stream
you should use Using
statement to dispose Stream after usage.
Upvotes: 4
Reputation: 176936
just check
if(ds.Tables["Images"].Rows[count - 1]["Image"]!=DbNull.Value)
{
//you code of execution
}
else
{
//display default image
}
Upvotes: 1