Wednesday, July 3, 2013

How to Store and Retrieve Images from Database and Display in Gridview in ASP.NET with C# - Example

Introduction:

Here in this post I explain how to store and retrieve images from database and also display images in gridview.

In this example i have used simple form in which your can upload his image using Fileupload control. this uploaded image is stored in to the project directory and the path of a directory with file name is stored into database. when  we bind gridview this path will be assigned to image control.

here is the image of form

Database Table:-

Source Code(in asp.net):-

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="GridViewwithoutRowCmd.aspx.cs" Inherits="_Default" %>

<!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></title>
    <style type="text/css">
        .auto-style1 {
            width: 100%;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <br />
        <asp:HiddenField ID="hid" runat="server" />
        <center>         
             <table class="auto-style1">
              <tr>
                  <td align="center">
        <asp:Literal ID="Literal1" runat="server" Text="Name"></asp:Literal>
                  </td>
                  <td align="left">
        <asp:TextBox ID="tname" runat="server"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" 
            ControlToValidate="tname" ErrorMessage="RequiredFieldValidator" 
            ValidationGroup="vreg"></asp:RequiredFieldValidator>
                  </td>
              </tr>
              <tr>
                  <td align="center">
        <asp:Literal ID="Literal2" runat="server" Text="Gender"></asp:Literal>
                  </td>
                  <td align="left">
        <asp:RadioButtonList ID="RadioButtonList1" runat="server" Height="16px" 
            RepeatDirection="Horizontal" Width="60px">
            <asp:ListItem Value="0">MALE</asp:ListItem>
            <asp:ListItem Value="1">FEMALE</asp:ListItem>
        </asp:RadioButtonList>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" 
            ControlToValidate="RadioButtonList1" ErrorMessage="RequiredFieldValidator" 
            ValidationGroup="vreg"></asp:RequiredFieldValidator>
                  </td>
              </tr>
              <tr>
                  <td align="center">
        <asp:Literal ID="Literal5" runat="server" Text="Image URL"></asp:Literal>
                  </td>
                  <td align="left">
        <asp:FileUpload ID="ImageUpload" runat="server" />
        <asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server" 
            ControlToValidate="ImageUpload" ErrorMessage="RequiredFieldValidator" 
            ValidationGroup="vreg"></asp:RequiredFieldValidator>
                  </td>
              </tr>
              <tr>
                  <td align="center">&nbsp;</td>
                  <td align="left">
    
        <asp:Button ID="badd" runat="server" Text="Add" onclick="badd_Click" 
            ValidationGroup="vreg"/>
    
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <asp:Button ID="bcancle" runat="server" Text="Cancle" onclick="bcancle_Click" />
    
                  </td>
              </tr>
              <tr>
                  <td colspan="2" align="center">
          <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
            CellPadding="4" ForeColor="#333333" 
            GridLines="None">
        <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
        <Columns>
             <asp:TemplateField HeaderText="id" Visible="false">
            <ItemTemplate>
                 <asp:Label ID="lid" runat="server" Text='<% #Eval("id")%>'></asp:Label>
            </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Name">
            <ItemTemplate>
                 <asp:Label ID="lname" runat="server" Text='<% #Eval("name")%>'></asp:Label>
            </ItemTemplate>
            </asp:TemplateField>
           
             <asp:TemplateField HeaderText="Gender">
            <ItemTemplate>
                      <asp:Label ID="lgender" runat="server" Text='<%# Eval("gender").ToString()=="0" ? "MALE":"FEMALE" %>'></asp:Label>
            </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Image">
                <ItemTemplate>
                    <asp:Image ID="Image1" runat="server" Height="200px" Width="200px" ImageUrl='<%#Eval("image") %>'/>
                </ItemTemplate>
            </asp:TemplateField>
             <asp:TemplateField>
                <ItemTemplate>
                    <asp:LinkButton ID="lbedit" runat="server" OnClick="editDetail">Edit</asp:LinkButton>
                    
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField>
            <ItemTemplate>
                <asp:LinkButton ID="lbdelete" runat="server" OnClick="deleteDetail">Delete</asp:LinkButton>
            </ItemTemplate>
            </asp:TemplateField>
            
        </Columns>
        <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
        <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
        <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
        <HeaderStyle BackColor="#090A0A" Font-Bold="True" ForeColor="White" />
        <EditRowStyle BackColor="#999999" />
        <AlternatingRowStyle BackColor="White" ForeColor="#0B0B0C" />
        </asp:GridView>
                  </td>
              </tr>
        </table>
        </center>


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

Code behind(in C#):-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page 
{
    static string str = @"Data Source=SQLDB;Persist Security Info=True;User ID=Demoh;Password=Demo1@";
    public static SqlConnection con = new SqlConnection(str);
    DataTable dtTemp = new DataTable();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            GridView1.DataSource = Data_of_Grid("select * from aby_GridviewWithoutRowCmd");
            GridView1.DataBind();
        }
    }

 protected void badd_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            if (badd.Text == "Add")
            {
                string ig = ImageUpload.FileName.ToString();
                    string url = "photo/" + ig;
                    ImageUpload.SaveAs(Server.MapPath("~//") + url);//this function will store the image in to you project

                Cmd_Non_Query("INSERT INTO aby_GridviewWithoutRowCmd(name,gender,image) VALUES ('" + tname.Text + "'," + RadioButtonList1.SelectedValue + ",'" + url + "')");
            }
            else
            {

                int i = Convert.ToInt32(hid.Value);
              
                string ig = ImageUpload.FileName.ToString();
                string url = "photo/" + ig;
                ImageUpload.SaveAs(Server.MapPath("~//") + url);
              
                if (Cmd_Scaler("select id from aby_GridviewWithoutRowCmd where id=" + hid.Value) != null)
                {
                    Cmd_Non_Query("UPDATE aby_GridviewWithoutRowCmd set name='" + tname.Text + "', gender=" + RadioButtonList1.SelectedValue + ", image='" + url + "' where id=" + hid.Value.ToString());
                }
                badd.Text = "Add";
            }

            GridView1.DataSource = Data_of_Grid("select * from aby_GridviewWithoutRowCmd");
            GridView1.DataBind();
        }
        clr();
    }
 protected void editDetail(object sender, EventArgs e)
 {

     LinkButton lb = (LinkButton)sender;
     GridViewRow gr = lb.NamingContainer as GridViewRow;

     Label lid1 = (Label)gr.FindControl("lid");
     hid.Value = lid1.Text;      //store the id of record into hiddenfield used when we actully submit changes 

     Label lname1 = (Label)gr.FindControl("lname");
     tname.Text = lname1.Text;

     Label lgender1 = (Label)gr.FindControl("lgender");
     RadioButtonList1.SelectedValue = RadioButtonList1.Items.FindByText(lgender1.Text).Value;

     Image im = (Image)gr.FindControl("Image1");


     badd.Text = "Update";
 }
 protected void deleteDetail(object sender, EventArgs e)
 {
     badd.Text = "Add";
     LinkButton lb = (LinkButton)sender;
     GridViewRow gr = lb.NamingContainer as GridViewRow;
     Image im = (Image)gr.FindControl("Image1");

     System.IO.File.Delete(Server.MapPath(im.ImageUrl));

     Label lid1 = (Label)gr.FindControl("lid");
     Cmd_Non_Query("delete from aby_GridviewWithoutRowCmd where id=" + lid1.Text);

     GridView1.DataSource = Data_of_Grid("select * from aby_GridviewWithoutRowCmd");
     GridView1.DataBind();
 }

public void clr()
    {
        tname.Text = "";
        RadioButtonList1.SelectedIndex = -1;
      
    }
    public void bcancle_Click(object sender, EventArgs e)
    {
        badd.Text = "Add";
        clr();
    }
    //functions for Database operations
    public DataTable Data_of_Grid(string q)
    {
        DataTable dt = new DataTable();
        try
        {
            if (con.State == ConnectionState.Closed)
            {
                con.Open();
            }
            SqlCommand cmd = new SqlCommand(q, con);
            SqlDataAdapter sd = new SqlDataAdapter();
            sd.SelectCommand = cmd;
            sd.Fill(dt);

        }
        catch (Exception err)
        {
            //TODO
        }
        finally
        {
            con.Close();
        }
        return dt;
    }
    public void Cmd_Non_Query(string q)
    {
        try
        {
            SqlCommand cmd = new SqlCommand(q, con);
            if (con.State == ConnectionState.Closed)
            {
                con.Open();
            }
            cmd.ExecuteNonQuery();
        }
        catch (Exception err)
        {
        }
        finally
        {
            con.Close();
        }

    }
    public Object Cmd_Scaler(string q)
    {
        if (con.State == ConnectionState.Closed)
        {
            con.Open();
        }

        SqlCommand cmd = new SqlCommand(q, con);
        string val = string.Empty;
        return cmd.ExecuteScalar();
        con.Close();

    }

 
}

No comments :

Post a Comment