Click here to Skip to main content
16,020,974 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello

I have a grid view, but the problem is while updating the gridview image is null.

What will be the issue.
I am getting an error while updating a row, the image columns displys cross, rest of all are updating correctly.


Also it displays null image while debugging code.
My code for aspx.cs is:
C#
public void bind()
{

conn.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM tbl_SqlImage", conn);
DataSet ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count != 0)
{
GridView1.DataSource = ds;
GridView1.DataBind();
}
conn.Close();

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//june25

GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
Label lblID = (Label)row.FindControl("lblID");
//Image Image = (Image)row.FindControl("Image1");
TextBox textName = (TextBox)row.FindControl("txtName");
TextBox textDesc = (TextBox)row.FindControl("txtDesc");
//TextBox textImage = (TextBox)row.FindControl("txtImage");
TextBox textActive = (TextBox)row.FindControl("txtActive");
TextBox textCreatedBy = (TextBox)row.FindControl("txtCreatedBy");
TextBox textCreatedDate = (TextBox)row.FindControl("txtCreatedDate");

//FileUpload FileUpload2 = (FileUpload)row.FindControl("FileUpload2");

FileUpload Image = (FileUpload)row.FindControl("FileUpload2");
//FileUpload FileUpload2 = (FileUpload)GridView1.Rows[e.RowIndex].FindControl("FileUpload2");

GridView1.EditIndex = -1;

conn.Open();



SqlCommand cmd = new SqlCommand("UPDATE tbl_SqlImage set Name='" + textName.Text + "' , Description='" + textDesc.Text + "' , Image='" + convertByte(Image) + "' , Active='" + textActive.Text + "' , CreatedBy='" + textCreatedBy.Text + "' , CreatedDate='" + textCreatedDate.Text + "' where ID='" + lblID.Text.Trim() + "' ", conn);
//SqlCommand cmd = new SqlCommand("UPDATE tbl_SqlImage set Name='" + textName.Text + "' , Description='" + textDesc.Text + "' , Image='" + textImage.Text + "' , Active='" + textActive.Text + "' , CreatedBy='" + textCreatedBy.Text + "' , CreatedDate='" + textCreatedDate.Text + "' where ID='" + lblID.Text.Trim() + "' ", conn);
cmd.ExecuteNonQuery();
conn.Close();
bind();
}


The code for aspx is:
XML
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="MainTable.aspx.cs" Inherits="commonlogin.MainTable" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>GridView</title>

    <link href="Content/StyleSheet1.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <form id="form1" runat="server">
    <div>

        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns ="False"
            AutoGenerateDeleteButton="True" onrowdeleted="GridView1_RowDeleted" AutoGenerateEditButton ="True"
            onrowdeleting="GridView1_RowDeleting" onrowediting="GridView1_RowEditing"
            onrowupdating="GridView1_RowUpdating"
            onpageindexchanging="GridView1_PageIndexChanging"
            onrowcancelingedit="GridView1_RowCancelingEdit" AllowPaging="True" CssClass ="bodytext"
            AllowSorting="True" CellPadding="3"
            GridLines="None" onselectedindexchanged="GridView1_SelectedIndexChanged"
            ForeColor="#333333" onrowdatabound="GridView1_RowDataBound"
            BorderStyle="Solid" BorderWidth="5px" CellSpacing="1" >


            <AlternatingRowStyle BackColor="White" ForeColor="#284775" />


        <Columns>


            <asp:TemplateField HeaderText="ID"  >
                <%--<EditItemTemplate>
                    <asp:TextBox ID="txtID" runat="server" Text='<%# Bind("ID") %>'></asp:TextBox>
                </EditItemTemplate>--%>
                <ItemTemplate>
                 <%--<asp:Label ID="Label1" runat="server" ImageUrl='<%# "Handler1.ashx?ID=" + Eval("ID")%>'  Text='<%# Bind("ID") %>'></asp:Label>--%>
                    <asp:Label ID="lblID" runat="server" CssClass="bodytext"   Text='<%# Bind("ID") %>'></asp:Label>
                </ItemTemplate>
                <ItemStyle HorizontalAlign="Left" />
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Name">
                <EditItemTemplate>
                    <asp:TextBox ID="txtName" runat="server" CssClass ="TextBox"  Text='<%# Bind("Name") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="lblName" runat="server" CssClass="bodytext"  Text='<%# Bind("Name") %>'></asp:Label>
                </ItemTemplate>
                <ItemStyle HorizontalAlign="Left" />
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Description">
                <EditItemTemplate>
                    <asp:TextBox ID="txtDesc" runat="server" CssClass ="TextBox"  Text='<%# Bind("Description") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="lblDesc" runat="server" CssClass="bodytext"  Text='<%# Bind("Description") %>'></asp:Label>
                </ItemTemplate>
                <ItemStyle HorizontalAlign="Left" />
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Image">
                <EditItemTemplate>
                    <%--<asp:TextBox ID="txtImage" runat="server" CssClass ="TextBox" EnableViewState="true"   Text='<%# Bind("Image") %>' ></asp:TextBox>--%>

                 <%--<asp:Image ID="Image1" runat="server"  EnableViewState="true"  ImageUrl='<%# "Handler1.ashx?ID=" + Eval("ID")%>'/>--%>
                    <asp:FileUpload ID="FileUpload2" runat="server" />
                <asp:Button ID="btnUpdate" runat="server" OnClick="btnUpdate_Click" Text="Update Image" />
                    <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
                <%--<asp:TextBox ID="txtImage" runat="server" CssClass ="TextBox"></asp:TextBox>--%>

                </EditItemTemplate>
                <ItemTemplate>
                <%--<asp:Image ID="Image1" runat="server"  EnableViewState="true"  ImageUrl='<%# "Handler1.ashx?ID=" + Eval("ID")%>'/>--%>

                <asp:Image ID="Image1" runat="server"  ImageUrl='<%# string.Format("Handler1.ashx?ID={0}",Eval("ID"))%>'/>

                <%-- <asp:FileUpload ID="FileUpload2" runat="server" />
                <asp:Button ID="btnUpdate" runat="server" OnClick="btnUpdate_Click" Text="Update Image" />
                    <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
--%>




                <%--<asp:Image ID="Image2" runat="server" ImageUrl='<%# "Handler1.ashx?ID=" + Bind("ID")%>'/>--%>

                    <%--<asp:Label ID="lblImage" runat="server"  Text='<%# Bind("Image") %>'></asp:Label>--%>

                    <%--<asp:Label ID="lblImage" runat="server"  ImageUrl='<%# "Handler1.ashx?ID=" + Eval("ID") %>'></asp:Label>--%>
                    <%--<asp:Label ID="Label1" runat="server" ImageUrl='<%# "Handler1.ashx?ID=" + Eval("ID")%>'  Text='<%# Bind("Image") %>'></asp:Label>--%>
                </ItemTemplate>

                <ItemStyle HorizontalAlign="Left" BackColor ="AliceBlue" />

                 <%--<asp:FileUpload ID="FileUpload2" runat="server" />
                <asp:Button ID="btnUpdate" runat="server" OnClick="btnUpdate_Click" Text="Update Image" />--%>
            </asp:TemplateField>

            <asp:TemplateField HeaderText="Active">
                <EditItemTemplate>
                    <asp:TextBox ID="txtActive" runat="server" CssClass ="TextBox" Text='<%# Bind("Active") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="lblActive" runat="server" CssClass="bodytext"  Text='<%# Bind("Active") %>'></asp:Label>
                </ItemTemplate>
                <ItemStyle HorizontalAlign="Left" />
            </asp:TemplateField>
            <asp:TemplateField HeaderText="CreatedBy">
                <EditItemTemplate>
                    <asp:TextBox ID="txtCreatedBy" runat="server" CssClass ="TextBox"  Text='<%# Bind("CreatedBy") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="lblCreatedBy" runat="server" CssClass="bodytext"  Text='<%# Bind("CreatedBy") %>'></asp:Label>
                </ItemTemplate>
                <ItemStyle HorizontalAlign="Left" />
            </asp:TemplateField>
            <asp:TemplateField HeaderText="CreatedDate">
                <EditItemTemplate>
                    <asp:TextBox ID="txtCreatedDate" runat="server" CssClass ="TextBox"  Text='<%# Bind("CreatedDate") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="lblCreatedDate" runat="server" CssClass="bodytext"  Text='<%# Bind("CreatedDate") %>'></asp:Label>

                </ItemTemplate>
                <ItemStyle HorizontalAlign="Left" />
            </asp:TemplateField>
            </Columns>
            <EditRowStyle BackColor="#999999" BorderStyle="Dotted" Width="5px" />
            <FooterStyle BackColor="#5D7B9D" ForeColor="White" Font-Bold="True" />
            <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
            <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
            <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
            <SortedAscendingCellStyle BackColor="#E9E7E2" />
            <SortedAscendingHeaderStyle BackColor="#506C8C" />
            <SortedDescendingCellStyle BackColor="#FFFDF8" />
            <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
            </asp:GridView><br />
            <%--<asp:FileUpload ID="FileUpload2" runat="server" />--%>
                <%--<asp:Button ID="btnUpdate" runat="server" OnClick="btnUpdate_Click" Text="Update Image" />
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>--%>
        <tr>

        <td>

        </div>

            <asp:HyperLink ID="HyperLink1" CssClass ="wishlist " NavigateUrl ="~/TableAdd.aspx" runat="server">AddNew</asp:HyperLink><br /><br />

        </td>
        </tr>
        <asp:label id="Messagelbl" forecolor="Red" CssClass="wishlist" runat="server"/>


    </form>
</body>
</html>


The code for Handler.aspx
C#
using System;
using System.Configuration;
using System.Web;
using System.IO;
using System.Data;
using System.Data.SqlClient;
namespace commonlogin
{
    /// <summary>
    /// Summary description for Handler1
    /// </summary>
    public class Handler1 : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            


            //June25
            Int32 nID;
            if (context.Request.QueryString["ID"] != null)
                nID = Convert.ToInt32(context.Request.QueryString["ID"]);
            else
                throw new ArgumentException("No paramter specified");

            context.Response.ContentType = "image/jpeg";
            Stream strm = ShowEmpImage(nID);
            byte[] buffer = new byte[4096];
            int byteSeq = strm.Read(buffer, 0, 4096);

            while (byteSeq > 0)
            {
                context.Response.OutputStream.Write(buffer, 0, byteSeq);
                byteSeq = strm.Read(buffer, 0, 4096);
                context.Response.BinaryWrite(buffer);
            }
            //june25
        }
        public Stream ShowEmpImage(int nID)
        {
            //june25
            string conn = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
            SqlConnection con = new SqlConnection(conn);
            string sql = "SELECT Image FROM tbl_SqlImage WHERE ID=@ID";
            SqlCommand cmd = new SqlCommand(sql, con);
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.AddWithValue("@ID", nID);
            con.Open();
            object img = cmd.ExecuteScalar();
            try
            {
                return new MemoryStream((byte[])img);
            }
            catch
            {
                return null;
            }
            finally
            {
                con.Close();
            }
            //june25
        }
        
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

I am getting an error while updating a row, the image columns displys cross.rest of all are updating correctly.
Posted
Updated 25-Jun-12 18:37pm
v3
Comments
Sandeep Mewara 26-Jun-12 5:42am    
Multiple reposts! :doh:

1 solution

Hello Nikil,

Please let us know the field type you are using to store image. Your code shows that you are converting to image to byte using convertByte(Image) method while saving into the database. However while retrieving you are directly binding to the grid. I suppose you need to convert the byte to image and then display in the grid. Please try converting the byte to image and then binding to grid. Also could you post the code present in
Handler1.ashx?ID={0}",Eval("ID"))%


Following link may help you :
http://www.aspsnippets.com/Articles/Display-images-from-SQL-Server-Database-in-ASP.Net-GridView-control.aspx[^]

Try below link for your handler code, hope it helps you:
http://stackoverflow.com/questions/5313377/handler-image-display-on-null-problem[^]
 
Share this answer
 
v4
Comments
Nikil0012 26-Jun-12 0:29am    
Filed type for storing image is Image in database
Nikil0012 26-Jun-12 0:30am    
And my image is displying correctly but while updating the issue comes
Nikil0012 26-Jun-12 0:35am    
I have posted the code for Handler.aspx, Please help
Vani Kulkarni 26-Jun-12 1:00am    
Updated the answer.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900