2014-02-26 123 views
0

我想從我的Access數據庫中獲取圖片到一個圖片框。 但是,當我試圖填補我的DataRow白衣DataSet中我得到以下錯誤:未將對象引用設置爲對象的實例。錯誤

Object reference not set to an instance of an object

任何幫助,將不勝感激! 我有以下代碼:

 OleDbConnection conn = new OleDbConnection(constr); 
     conn.Open(); 

     string cmdstr = "SELECT Picture FROM Gegevens WHERE ID =" + id; 
     OleDbCommand cmd = new OleDbCommand(cmdstr, conn);   
     OleDbDataAdapter da = new OleDbDataAdapter(cmd); 

     DataSet ds = new DataSet(); 
     da.Fill(ds, "picture"); 

     DataRow dr = ds.Tables["Pictures"].Rows[0]; //Here i get the error! 

     byte[] result = (byte[])dr["Picture"]; 
     int ArraySize = result.GetUpperBound(0); 

     MemoryStream ms = new MemoryStream(result, 0, ArraySize); 
     Picturebox1.Image = Image.FromStream(ms); 

     conn.Close(); 

回答

1

的ds.Tables [「圖片」]返回空值,所以你不能讓行。嘗試:

ds.Tables[0].Rows[0]; 

ds.Tables["picture"].Rows[0]; 
0

您需要檢查數據集是否爲空或不使用它之前

嘗試這樣

 OleDbConnection conn = new OleDbConnection(constr); 
     conn.Open(); 

     string cmdstr = "SELECT Picture FROM Gegevens WHERE ID =" + id; 
     OleDbCommand cmd = new OleDbCommand(cmdstr, conn);   
     OleDbDataAdapter da = new OleDbDataAdapter(cmd); 

     DataSet ds = new DataSet(); 
     da.Fill(ds, "picture"); 

     if (ds != null && Data.Tables[0].Rows.Count > 0) 
     { 
     DataRow dr = ds.Tables["Pictures"].Rows[0]; //Here i get the error! 

     byte[] result = (byte[])dr["Picture"]; 
     int ArraySize = result.GetUpperBound(0); 

     MemoryStream ms = new MemoryStream(result, 0, ArraySize); 
     Picturebox1.Image = Image.FromStream(ms); 
     } 
     conn.Close(); 
相關問題