2013-02-16 12 views
0

嗨,朋友,我已經插入圖像到Sql Server,我需要檢索圖像從SQL Server 2008 R2到Datagridview列在C#[Windows應用程序]。是否有可能在數據網格視圖中顯示圖像是網格視圖列中的任何相應大小。如何檢索從SQL Server 2008 R2到Datagridview在C#中的圖像[Windows應用程序]

我的編碼插入圖像到SQL Server是:

public void saveImageInDataBase(int imageid) 
    { 

     byte[] imagedata = ReadImageFile(txt_upload.Text); 
     SqlConnection sqlconn = new SqlConnection(); 
     sqlconn.ConnectionString = "Data Source=.;Initial Catalog=db_payroll;Integrated Security=True;"; 
     sqlconn.Open(); 
     string query = "insert into tbl_image values('"+imagedata+"')"; 
     MessageBox.Show(query); 
     SqlCommand cmd = new SqlCommand(query, sqlconn); 
     int rows = cmd.ExecuteNonQuery(); 
     if (rows > 0) 
     { 
      MessageBox.Show("Image saved."); 
      txt_upload.Text = ""; 
      pictureBox1.Image = null; 
     } 
     else 
     { 
      MessageBox.Show("Unable to save image."); 
      sqlconn.Close(); 
     } 
    } 

    public byte[] ReadImageFile(string imageLocation) 
    { 
     byte[] imageData = null; 
     FileInfo fileInfo = new FileInfo(imageLocation); 
     long imageFileLength = fileInfo.Length; 
     FileStream fs = new FileStream(imageLocation, FileMode.Open, FileAccess.Read); 
     BinaryReader br = new BinaryReader(fs); 
     imageData = br.ReadBytes((int)imageFileLength); 
     return imageData; 
    } 

請嘗試解決這個問題。由於

回答

4

商店DB(DB中的imagedata列必須有IMAGE數據類型)

string query = "insert into tbl_image values(@imagedata)"; 
    SqlCommand cmd = new SqlCommand(query, sqlconn); 
    cmd.Parameters.Add("@imagedata", System.Data.SqlDbType.Image); 
    cmd.Parameters["@imagedata"].Value = imagedata; 
    int rows = cmd.ExecuteNonQuery(); 

從DB

檢索
string query = "select imagedata from tbl_image where [email protected]"; 
    SqlCommand cmd = new SqlCommand(query, sqlconn); 
    cmd.Parameters.AddWithValue("@id", id); 
    byte[] imagedata=(byte[])cmdSelect.ExecuteScalar(); 
+0

其作品很好...你能告訴我,如何將單元格大小修改爲100 X 100,圖像樣式應該像拉伸一樣。 – coolprarun 2013-02-16 14:41:52

+0

@coolprarun爲此,您可以使用'Ask Question'按鈕並使用適當的標題創建新線程。 – 2013-02-16 14:55:23

相關問題