2011-07-24 123 views
-1

我有一個問題,當我從內存流中的數據庫檢索圖像時,它會給出錯誤Parameter is not valid。請幫我解決這個問題。從SQL Server數據庫檢索圖像

代碼:

private void button3_Click(object sender, EventArgs e) 
{ 
    string strcon = "Data Source=PINKAL-PC; initial catalog=testing; integrated security=SSPI;"; 

    SqlConnection sqlcon = new SqlConnection(strcon); 
    sqlcon.Open(); 

    string strquery = "select * from testimg"; 

    SqlDataAdapter da = new SqlDataAdapter(strquery,sqlcon); 
    DataSet ds = new DataSet(); 
    da.Fill(ds); 

    DataTable dt = new DataTable(); 
    dt = ds.Tables[0]; 

    byte[] barrImg = (byte[])dt.Rows[7]["image"]; 
    MemoryStream mstream = new MemoryStream(barrImg); 

    pictureBox2.Image = Image.FromStream(mstream); 
} 
+2

錯誤在哪一行發生? – Tim

+0

什麼**列表**你的表'testimg'包含?很可能,您在訪問數據時只是拼錯了列名。 –

回答

2

不知道你的問題的真正根源是 - 我的猜測是,有是在你的數據庫表testimgimage名字沒有列,但是你想閱讀該欄目以獲取您的照片。

但這裏有幾件事情我會建議爲你的代碼一般:

private void button3_Click(object sender, EventArgs e) 
{ 
    string strcon = "Data Source=PINKAL-PC; initial catalog=testing; integrated security=SSPI;"; 

    // Put your SqlConnection into using blocks to ensure proper disposal 
    using(SqlConnection sqlcon = new SqlConnection(strcon)) 
    { 
    // sqlcon.Open(); -- don't open it here already - open as LATE as possible.... 
    // for SqlDataAdapter - you don't even need to open it yourself - 
    // the data adapter will do this automatically for you 
    // and **IF** you open it yourself - you also need to CLOSE it again! 

    // *NEVER* use SELECT * in code !! specify the columns you want explicitly 
    // string strquery = "select * from testimg"; 
    string strquery = "SELECT col1, col2, col3 ..... FROM dbo.testimg"; 

    SqlDataAdapter da = new SqlDataAdapter(strquery, sqlcon); 

    //DataSet ds = new DataSet(); if you only want a single DataTable - no point in having a whole DataSet ! That's just overhead..... 
    //da.Fill(ds); 
    //DataTable dt = new DataTable(); 
    //dt = ds.Tables[0]; 
    DataTable dt = new DataTable(); 
    da.Fill(dt); 

    // is there a "image" column in your table?? 
    // You need to use the proper column name here! 
    byte[] barrImg = (byte[])dt.Rows[7]["image"]; 
    MemoryStream mstream = new MemoryStream(barrImg); 

    pictureBox2.Image = Image.FromStream(mstream); 
    } 
} 
+0

問題保持不變,列名和數據庫名稱正確。我應該爲此做些什麼。 – user721563

+0

@ user721563:你能告訴我們你的表結構嗎?列名和數據類型 –

0

如果你的錯誤是關於將圖像從數據庫轉換成流,只是試圖修改這樣的代碼: :

byte[] barrImg = (byte[])dt.Rows[7]["image"]; 

MemoryStream mstream = new MemoryStream(); 

mstream .Write (barrImg, 0, barrImg.Length);  
mstream .Seek (0, SeekOrigin.Begin);   
mstream .Close(); 

pictureBox2.Image = Image.FromStream(mstream); 
+0

你爲什麼試圖從封閉的流中訪問對象?這是如何工作的? – Debaprasad

相關問題