Noelle
Noelle

Reputation: 782

Display an image in a Image container in WPF

I am trying to display an image in an WPF Image container

string imageContent = ((DataRowView)dgQuestions.SelectedItem)["QuestionImage"].ToString();
if (imageContent.Length >= 5)
{
    byte[] data = (byte[])((DataRowView)dgQuestions.SelectedItem)["QuestionImage"];
    ImageSourceConverter imgConv = new ImageSourceConverter();
    imageSource = (ImageSource)imgConv.ConvertFromString(data.ToString());
}

The last line of the above code generates the following error

object reference not set to an instance of an object

I'm not bothered with how the datagrid displays the image as the user will never see the it.

This is how I am filling the grid:

SqlCommand cmd = new SqlCommand();
cmd.Connection = Con;
cmd.CommandText = "getQuizQuestions";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@quizid", SqlDbType.Int)).Value = quizId;
cmd.ExecuteNonQuery();
SqlDataAdapter daSubject = new SqlDataAdapter(cmd);
DataSet dsSubject = new DataSet();
daSubject.Fill(dsSubject, "QuizSubject");
dgQuestions.ItemsSource = dsSubject.Tables[0].DefaultView;

Upvotes: 0

Views: 2321

Answers (1)

Erre Efe
Erre Efe

Reputation: 15557

Set a breakpoint and validate data isn't null. Also, why don't you set the image source as the byte[] instead of using a ToString():

public BitmapImage ImageFromBuffer(Byte[] bytes)
{
    MemoryStream stream = new MemoryStream(bytes);
    BitmapImage image = new BitmapImage();
    image.BeginInit();
    image.StreamSource = stream;
    image.EndInit();
    return image;
}

public Byte[] BufferFromImage(BitmapImage imageSource)
{
    Stream stream = imageSource.StreamSource;
    Byte[] buffer = null;
    if (stream != null && stream.Length > 0)
    {
        using (BinaryReader br = new BinaryReader(stream))
        {
            buffer = br.ReadBytes((Int32)stream.Length);
        }
    }

    return buffer;
}

Upvotes: 1

Related Questions