Displaying Images In GridView From DataBase

Previous article I explained about GridviewPaging And GridviewSorting

This is a simple web application for users who are new to ASP.NET. This will show how we can retrieve an image from a database and display it in a GridView.

To start with, let me explain the SQL Server database table structure we are going to use to Get the image. The table you are going to Get as follows:


:Here I am using Empoyee table :


Image table



 Here I am joining Employee table and image table results:



Drag the Gridview from toolbox DataControls and then set the essential properties


<asp:GridView runat="server" ID="gvEmpdetails" DataKeyNames="EmpID" AllowPaging="True"
AutoGenerateColumns="false"
OnPageIndexChanging="gvEmpdetails_OnPageIndexChanging">
<RowStyle BackColor="#EFF3FB" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
<Columns>           
<asp:BoundField DataField="EmpID" HeaderText="EmpID" SortExpression="EmpID" />
<asp:BoundField DataField="EmpName" HeaderText="EmpName" SortExpression="EmpName" />
<asp:BoundField DataField="EmpSal" HeaderText="EmpSal" SortExpression="EmpSal" />
<asp:BoundField DataField="EmpBranch" HeaderText="EmpBranch" SortExpression="EmpBranch" />
<asp:BoundField DataField="EmpCode" HeaderText="EmpCode" SortExpression="EmpCode" />
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:Image ID="img" ImageUrl='<%# Eval("Image")%>' Width="40px" Height="40px" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>





In the code behind page write the code as below:
public partial class DisplayingImageinGridView : System.Web.UI.Page

{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //Binding Data From Database
            bindGridView();
        }
    }

    public void bindGridView()
    {
        //sql connection
        SqlConnection con = new SqlConnection("Data Source=TAPA-PC;user Id=sa;password=123;DataBase=Customer");
        SqlDataAdapter mySqlAdapter = new SqlDataAdapter("select EmpID,EmpName,EmpSal,EmpBranch,EmpCode,img.ImageURL as Image from Employee as emp inner join Image as img on img.ImageID=emp.EmpID", con);
        DataSet myDataSet = new DataSet();
        mySqlAdapter.Fill(myDataSet);

        //Binding Data to gridview...
        gvEmpdetails.DataSource = myDataSet;
        gvEmpdetails.DataBind();

    }

}
ScreenShots:

0 Responses to “Displaying Images In GridView From DataBase”

Post a Comment

Labels

Topics