locked
Update image binary data in grid RRS feed

  • Question

  • User-524584285 posted

    Hello,

    i have stored the image file in a database as a varbinary(max) data farmate,

    my problem is,

    data from database is displaying properly in gridview,but while in a update if i not choose any new file than the image column will be updated as null, instead of that i want update that column with the existing bytes. how can i achieve please help me out

    ***my aspx page is:***

    <html>
    <body>
    <form id="form1" runat="server">
    <div>
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
    DataKeyNames="id" OnRowEditing="OnRowEditing"
    OnRowDataBound="RowDataBound" OnRowUpdating="OnRowUpdating">
    <Columns>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="Image">
    <ItemTemplate>
    <asp:Image ID="Image1" runat="server" Height="100px"
    Width="100px"
    ImageUrl='<%#"data:Image/jpg;base64,"+Convert.ToBase64String((byte[])Eval("Profile")) %>' />
    <asp:HiddenField ID="imgurl" runat="server" Value='<%# Eval("Profile") %>' />
    </ItemTemplate>
    <EditItemTemplate>
    <asp:HiddenField ID="hdProductPhoto" runat="server"
    Value='<%#"data:Image/jpg;base64,"+Convert.ToBase64String((byte[])Eval("Profile")) %>' />
    <asp:FileUpload ID="imgUpload" runat="server" /></td>
    </EditItemTemplate>
    </asp:TemplateField>
    </Columns>
    </asp:GridView>
    </div>
    </form>
    </body>
    </html>

    **my c sharp code is:**

    protected void OnRowUpdating(object sender, GridViewUpdateEventArgs e)
    {
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["studentReg"].ConnectionString);
    SqlCommand cmd = new SqlCommand("[studUpdate]", con);

    FileUpload fuPhoto = GridView1.Rows[e.RowIndex].FindControl("imgUpload") as FileUpload;
    byte[] ImageContent=null;


    if (fuPhoto.FileName == "")
    {
    // i want this section to be proper
    HiddenField hdProductPhoto =
    (HiddenField)GridView1.Rows[e.RowIndex].FindControl("hdProductPhoto");
    string imgvalue = hdProductPhoto.Value;
    Response.Write("<script>alert('" + hdProductPhoto.Value + "')</script>");

    }
    else
    {
    int length = fuPhoto.PostedFile.ContentLength;
    ImageContent = new byte[length];
    HttpPostedFile img = fuPhoto.PostedFile;
    img.InputStream.Read(ImageContent, 0, length);
    }
    string drpList = ddl.SelectedValue.ToString();
    string rdbTemp = rbl.SelectedValue.ToString();
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("@id", sid);
    cmd.Parameters.AddWithValue("@Profile", (byte[])ImageContent);
    cmd.Parameters.AddWithValue("@Action", "UPDATE");
    con.Open();
    cmd.ExecuteNonQuery();
    con.Close();
    }

    Monday, July 24, 2017 12:08 PM

All replies

  • User2103319870 posted

    but while in a update if i not choose any new file than the image column will be updated as null, instead of that i want update that column with the existing bytes. how can i achieve please help me out

    An easy way is to don't have image column in your update stored procedure when user didn't select any image in fileupload control.  

    Create two SPs one with Image column and one with out image column. If user calls update with out image selected on file upload then call the sp with out image column and call the SP with image column if user selects a file in fileupload control

    protected void OnRowUpdating(object sender, GridViewUpdateEventArgs e)
            {
               
                FileUpload fuPhoto = GridView1.Rows[e.RowIndex].FindControl("imgUpload") as FileUpload;
                byte[] ImageContent = null;
                string drpList = ddl.SelectedValue.ToString();
                string rdbTemp = rbl.SelectedValue.ToString();
    
                if (fuPhoto.FileName == "")
                {
                    //// i want this section to be proper 
                    //HiddenField hdProductPhoto =
                    //(HiddenField)GridView1.Rows[e.RowIndex].FindControl("hdProductPhoto");
                    //string imgvalue = hdProductPhoto.Value;
                    //Response.Write("<script>alert('" + hdProductPhoto.Value + "')</script>");
                    using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["studentReg"].ConnectionString))
                    {
                        try
                        {
                            con.Open();
                            //Change the procedure name which update all value except image column
                            SqlCommand cmd = new SqlCommand("[studUpdatewithoutimagecolumn]", con);
                            cmd.CommandType = CommandType.StoredProcedure;
                            cmd.Parameters.AddWithValue("@id", sid);
                            cmd.Parameters.AddWithValue("@Action", "UPDATE");
    
                            //Execute Query
                            cmd.ExecuteNonQuery();
                        }
                        catch (Exception ex)
                        {
                            throw new Exception(ex.Message);
                        }
                    }
                }
                else
                {
                    int length = fuPhoto.PostedFile.ContentLength;
                    ImageContent = new byte[length];
                    HttpPostedFile img = fuPhoto.PostedFile;
                    img.InputStream.Read(ImageContent, 0, length);
    
                    using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["studentReg"].ConnectionString))
                    {
                        try
                        {
                            con.Open();
                            //User Selected Image then update the image column with image content
                            SqlCommand cmd = new SqlCommand("[studUpdate]", con);
                            cmd.CommandType = CommandType.StoredProcedure;
                            cmd.Parameters.AddWithValue("@id", sid);
                            cmd.Parameters.AddWithValue("@Profile", (byte[])ImageContent);
                            cmd.Parameters.AddWithValue("@Action", "UPDATE");
                            //Execute Query
                            cmd.ExecuteNonQuery();
                        }
                        catch (Exception ex)
                        {
                            throw new Exception(ex.Message);
                        }
                    }
                }
            }

    Monday, July 24, 2017 1:23 PM