簡體   English   中英

如何在C#中將圖像從SQL Server 2008 R2檢索到Datagridview [Windows應用程序]

[英]How to retrieve image from SQL Server 2008 R2 to Datagridview in C# [Windows Application]

嗨,朋友們,我已經將圖像插入到Sql Server中,並且我需要從SQL Server 2008 R2檢索圖像到C#[Windows應用程序]中的Datagridview列。是否有可能在Data Grid View中顯示該圖像,而該圖像在網格視圖。

我將圖像插入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;
    }

請嘗試解決此問題。 謝謝

存儲到數據庫(在數據庫中, 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();

從數據庫檢索

    string query = "select imagedata from tbl_image where ID=@ID";
    SqlCommand cmd = new SqlCommand(query, sqlconn);
    cmd.Parameters.AddWithValue("@id", id);
    byte[] imagedata=(byte[])cmdSelect.ExecuteScalar();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM