2012-08-05 127 views
0

我創建了一個加載圖像並將其保存到數據庫中的表單。如何爲圖像設置NULL值

如果用戶沒有選擇任何圖像,我想將NULL值保存到數據庫中。

我試過這段代碼:

drow[1] = string.IsNullOrEmpty(imgData.ToString()) ? DBNull.Value : (object)imgData; 

,但它給了我這個錯誤:

Object reference not set to an instance of an object

這是我用來加載圖像的代碼:

private void simpleButton5_Click_1(object sender, EventArgs e) 
{ 
    try 
    { 
     if (openFileDialog1.ShowDialog() == DialogResult.OK) 
     { 
      picture.ImageLocation = openFileDialog1.FileName; 

      imgData = File.ReadAllBytes(openFileDialog1.FileName); 
     } 
    } 
    catch (Exception ex) 
    { 
     // Could not load the image - probably related to Windows file system permissions. 
     XtraMessageBox.Show(String.Format("Cannot display the image.\n You may not have permission to read the file, or it may be corrupt.\n\nReported error: {0}", ex.Message)); 
    } 
} 
+0

你爲什麼在'imgData'上調用'ToString()'?如果'imgData'爲'null'則會引發異常。 – Oded 2012-08-05 16:49:52

+0

我認爲更多的代碼會有所幫助。什麼是imgData的類型?卓爾的類型是什麼,它的運行時價值是多少? – lesscode 2012-08-05 17:05:23

回答

2

你是在這一行中做一些不必要的事情。沒有必要使用ToString()這實際上是有害的,因爲如果imgDatanull,您將獲得NullReferenceException。只需將該值直接與null進行比較即可。

這將是更好的,以及免疫到NullReferenceException

drow[1] = imgData == null ? DBNull.Value : (object)imgData; 
+0

感謝它的工作 – 2012-08-05 17:03:37

+0

或(稍微更緊湊): 卓爾[1] = imgData ?? (對象)DBNull.Value; – 2012-08-09 06:11:11

0

無論是可變卓爾或爲imageData爲null。他們需要引用一個對象才能執行數組解引用或調用ToString()。調試器應該能夠告訴你哪個變量是罪魁禍首。