Search code examples
c#sqlvisual-studiowinformspicturebox

How to load an image that is stored in a database into a picturebox object with C# and SQL


When doubling clicking a row in datagrid object within the following windows form, the relevant information properly displays in a secondary form.

enter image description here enter image description here

However I am not sure how to make it so that the image also displays in picturebox within the Student Form.

Here is the code so far:

public bool IsUpdate { get; set; }

        private void StudentForm_Load(object sender, EventArgs e)
        {
            //For Update Process
            if (this.IsUpdate == true)
            {
                using (SqlConnection con = new SqlConnection(AppConnection.GetConnectionString()))
                {
                    using (SqlCommand cmd = new SqlCommand("usp_Student_ReloadDataForUpdate", con))
                    {
                        cmd.CommandType = CommandType.StoredProcedure;

                        cmd.Parameters.AddWithValue("@StudentName", this.StudentName);

                        if (con.State != ConnectionState.Open)
                            con.Open();

                        DataTable dtStudent = new DataTable();

                        SqlDataReader sdr = cmd.ExecuteReader();

                        dtStudent.Load(sdr);

                        DataRow row = dtStudent.Rows[0];

                        StudentNameTextBox.Text = row["StudentName"].ToString();
                        AgeTextBox.Text = row["Age"].ToString();
                        GenderTextBox.Text = row["Gender"].ToString();
                        DescriptionTextBox.Text = row["Description"].ToString();
                        //IdPictureBox.Image = row["Image"].???

                        SaveButton.Text = "Update Student Information";
                        DeleteButton.Enabled = true;
                    }
                }
            }

This follow is the stored procedure for the method above:

CREATE PROCEDURE usp_Student_ReloadDataForUpdate
(
    @StudentName NVARCHAR(200)
)
AS
    BEGIN

        SELECT [StudentId]
              ,[StudentName]
              ,[Age]
              ,[Gender]
              ,[Description]
              ,[Image]
          FROM [dbo].[Students]
          WHERE StudentName = @StudentName
    END

This is how the data is saved in the database

        private void SaveButton_Click(object sender, EventArgs e)
        {
            if(IsFormValid())
            {
                //Do Update Process
                using (SqlConnection con = new SqlConnection(AppConnection.GetConnectionString())) //connect to database using AppConnection class and GetConnectionString method
                {
                    using (SqlCommand cmd = new SqlCommand("usp_Student_InsertNewStudent", con))
                    {
                        cmd.CommandType = CommandType.StoredProcedure;

                        cmd.Parameters.AddWithValue("@StudentName", StudentNameTextBox.Text.Trim());
                        cmd.Parameters.AddWithValue("@Age", AgeTextBox.Text.Trim());
                        cmd.Parameters.AddWithValue("@Gender", GenderTextBox.Text.Trim());
                        cmd.Parameters.AddWithValue("@Description", DescriptionTextBox.Text.Trim());
                        var image = IdPictureBox.Image;
                        using (var ms = new MemoryStream())
                        {
                            image.Save(ms, image.RawFormat);
                            cmd.Parameters.Add("@Image", SqlDbType.VarBinary).Value = ms.ToArray();
                        }
                        cmd.Parameters.AddWithValue("@CreatedBy", LoggedInUser.UserName);


                        if (con.State != ConnectionState.Open)
                            con.Open();

                        cmd.ExecuteNonQuery();

                        MessageBox.Show("Student is successfully updated in the database.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        ResetFormControl();
                    }
                }
            }


Solution

  • The data stored is a byte[] (Varbinary). You should convert it to an Image:

    var pic = (byte[])row["Image"];
    if (pic != null)
    {
       using (MemoryStream ms = new MemoryStream(pic))
       {
        IdPictureBox.Image = Image.FromStream(ms);
       }
    }
    

    PS: I am not commenting on the rest of your code, like you shouldn't use AddWithValue but Add.