Saturday 6 April 2013

Display images in GridView control from DataBase in Asp.net


Display images in GridView control from DataBase in Asp.net




In this article, I am explaining how to store images in database and display images from database in the GridView Control. 

Now follow steps as given below 

Steps [1] Design image table which has stored the images



Steps [2] Create store procedure for insert image in table

create   proc [dbo].[insert_catagory](@imagid int , @image_name varchar(50),
             @imp_path varchar(250)) as

  insert into image(image_id,image_name,image_path)
      values(@imagid,@image_name, @imp_path)


Steps [3] Default.aspx

<body>
    <form id="form1" runat="server">
    <table>
        <tr>
            <td>
                <asp:Label ID="lable1" runat="server"></asp:Label>
            </td>
        </tr>
        <tr>
            <td>
                Image id:
            </td>
            <td>
                <asp:TextBox ID="txtImageId" runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td>
                Image Name:
            </td>
            <td>
                <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td>
                Upload Image:
            </td>
            <td>
                <asp:FileUpload ID="FileUpload1" runat="server" />
            </td>
        </tr>
        <tr>
            <td>
            </td>
            <td>
                <asp:Button ID="Button1" runat="server" Text="submit" OnClick="Button1_Click" />
            </td>
        </tr>
        <tr>
            <td>
                &nbsp;
            </td>
        </tr>
        <tr>
            <td>
                &nbsp;
            </td>
            <td>
                <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowCancelingEdit="GridView1_RowCancelingEdit"
                    OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" OnRowDeleting="GridView1_RowDeleting">
                    <Columns>
                        <asp:BoundField DataField="image_id" HeaderText="Image ID" ReadOnly="True" />
                        <asp:BoundField DataField="image_name" HeaderText="Image Name" />
                        <asp:BoundField DataField="image_path" HeaderText="Image Path" />
                        <asp:TemplateField HeaderText="image">
                            <ItemTemplate>
                                <asp:Image ID="Image1" runat="server" Width="40px" Height="40px" ImageUrl='<%#DataBinder.Eval(Container,"DataItem.image_path") %>' />
                            </ItemTemplate>
                            <EditItemTemplate>
                                <asp:FileUpload ID="FileUpload1" runat="server" />
                            </EditItemTemplate>
                        </asp:TemplateField>
                        <asp:CommandField ShowEditButton="True" HeaderText="Edit" />
                        <asp:CommandField HeaderText="Delete" ShowDeleteButton="True" />
                    </Columns>
                </asp:GridView>
            </td>
        </tr>
    </table>
    </form>
</body>


Steps [4] Default.aspx.cs


using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page 
{
   
    SqlConnection con = new SqlConnection("Data Source=NEERAJ-PC;Initial Catalog=neeraj;User ID=sa;pwd=sa");
    SqlCommand cmd;
    SqlDataAdapter da;
    DataSet ds;
    static int a = 0;


    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGrid();
           
        }
    }
   
    protected void Button1_Click(object sender, EventArgs e)
    {
         string str = Server.MapPath(@"Image/");
        FileUpload1.SaveAs(str + FileUpload1.FileName);
        string s3 = FileUpload1.FileName;
       
        int m = Convert.ToInt32(txtImageId.Text);
        con.Open();
        int n =add_catagory(m, txtName.Text, s3);
        if (n == 1)
        {
            Response.Write("Record inserted sucessfully");
            txtImageId.Text = "";
            txtName.Text = "";
        }
        BindGrid();
            
     }
    public int add_catagory(int s1, string s2, string s3)
    {
         cmd = new SqlCommand("insert_catagory", con);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@imagid", SqlDbType.Int).Value = s1;
        cmd.Parameters.AddWithValue("@image_name", SqlDbType.VarChar).Value = s2;
        cmd.Parameters.AddWithValue("@imp_path", SqlDbType.VarChar).Value = s3;
        int k = cmd.ExecuteNonQuery();
       
        return k;
    }
    public void BindGrid()
    {
        
         da = new SqlDataAdapter("select * from image", con);
         ds = new DataSet();
        da.Fill(ds, "t1");
        GridView1.DataSource = ds.Tables[0];
        GridView1.DataBind();
        if (a == 0)
        {
            int n = ds.Tables[0].Rows.Count;
            for (int i = 0; i < n; i++)
            {
                string file = ds.Tables[0].Rows[i][2].ToString();
                string path = "Image/" + file;
                Image im = (Image)GridView1.Rows[i].FindControl("Image1");
                im.ImageUrl = path;
            }
            a = 1;
        }
    }
   
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        BindGrid();

    }


    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;
        a = 0;
        BindGrid();

    }
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        int img_id = Convert.ToInt32(GridView1.Rows[e.RowIndex].Cells[0].Text);
        FileUpload fp = (FileUpload)GridView1.Rows[e.RowIndex].FindControl("FileUpload1");
        TextBox img_name = (TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0];
        TextBox imp_path = (TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[0];
        string imagepath = fp.FileName;
        string s1 = Convert.ToString(img_name.Text);
        string s3 = "IMAGE/" + fp.FileName;
        if (fp.FileName == "")
        {
            s3 = imagepath;
        }
        else
        {
            fp.SaveAs(Server.MapPath("Image/" + fp.FileName));
        }

        string s = "update  image  set image_name='" + s1 + "',image_path='" + imagepath + "' where image_id=" + img_id;
        execcutecommand(s);
        GridView1.EditIndex = -1;
        a = 0;
        BindGrid();

    }
    public void execcutecommand(string s)
    {
         cmd = new SqlCommand(s, con);
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();
    }
    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int id = Convert.ToInt32(GridView1.Rows[e.RowIndex].Cells[0].Text);
        string s = "delete from image where image_id =" + id;
        execcutecommand(s);
        a = 0;
        BindGrid();
    }
    
}


The figure below displays the GridView with the images from database



1 comment: