Display images in Gridview in ASP.NET.

Display images in Gridview in ASP.NET.

In this article I am displaying images inside Gridview.
We can use it in many case  ,in general if we want to display country and their flag we can use it.

So here its code.


Step 1: Design DataBase Table


CREATE TABLE [dbo].[file_upload](
      [Id] [int] IDENTITY(1,1) NOT NULL,
      [FileName] [varchar](50) NULL,
      [path] [varchar](50) NULL,
     
) ON [PRIMARY]



Step 2: Design web form .aspx page


<asp:TextBox ID="txt_name" runat="server"  Text="Enter Name."></asp:TextBox>
           <asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="Upload" BackColor="YellowGreen" />
<br />
            <br />
            <asp:GridView ID="gr2" runat="server" AutoGenerateColumns="false" ShowHeader="false">
    <Columns>
        <asp:BoundField DataField="filename" />
        <asp:ImageField DataImageUrlField="path" ControlStyle-Height="100" ControlStyle-Width="100" />
    </Columns>
</asp:GridView>

Step 3: Logic on .Cs page


SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=xyz;User ID=sa;Password=******");
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
    string qu = "select * from file_upload";
            SqlDataAdapter ad = new SqlDataAdapter(qu,con);
            DataTable dt = new DataTable();
            ad.Fill(dt);
            gr2.DataSource = dt;
            gr2.DataBind();
        }

    }


protected void Upload(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile)
        {
            string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
            FileUpload1.PostedFile.SaveAs(Server.MapPath("~/Images/") + fileName);
         
            con.Open();
            string path = "~/Images/" + fileName;
         
            string qu = "insert into file_upload (FileName,path)values ('" +     txt_name.Text + "','" + path + "')";
            SqlCommand cmd = new SqlCommand(qu, con);
            cmd.ExecuteNonQuery();
            Response.Redirect(Request.Url.AbsoluteUri);


          


        }
    }




It will look like :




Comments

Popular posts from this blog

Create and save QR code in asp.net with C#

Change text of RadGrid Header Dynamically

Telerik Radwindow Open on Button Click