2012-04-25 51 views
0

我試圖在一個WPF圖像容器到顯示的圖像顯示的圖像在一個圖像容器中WPF

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

上述代碼的最後一行生成以下錯誤

對象引用沒有設置爲對象的實例

我不打擾datagrid如何顯示圖像,因爲用戶永遠不會看到它。

這是怎麼了填充網格:

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; 
+0

您是否使用了調試器來檢查'data'是否爲空?爲什麼你不使用ConvertFromString(imageContent)? – Phil 2012-04-25 14:06:09

+0

imageContent包含「System.Byte []」我正在使用它來確保有數據要進入數據 – Noelle 2012-04-25 14:25:57

回答

1

設置斷點並驗證數據不爲空。此外,爲什麼不將圖像源設置爲字節[]而不是使用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; 
}