Sunday, 18 June 2017

How to display image icons according to file extensions in asp.net

How to display image icons according to file extensions in asp.net
Description:
In this example we explain that how to display File Icon according to file extensions in Asp.Net using C#.or how to display image icons according to file extensions in asp.net.or show icons corresponding to the file type in asp.net.or displaying icons according to a file type in GridView in asp.net.or show File Icons with Filename in asp.net Gridview.or displaying pretty file icons in your Gridview in asp.net.so there are many question raised to displaying file icons according to file types in GridView in asp.net.

So here we demonstrate how to Bind Gridview with File Icons corresponding to its file types in asp.net.
Aspx Page:

  <asp:GridView ID="Grd_Employee" runat="server" AutoGenerateColumns="false"
            onrowdatabound="Grd_Employee_RowDataBound">
        <Columns>
        <asp:TemplateField HeaderText="File Name">
                    <ItemTemplate>                  
                    <img id="fileImage" runat="server"/>
                        <asp:HiddenField ID="HiddenField1" runat="server" Value='<%# Eval("Filepath") %>' />
                         <%# Eval("FileName"%>
                    </ItemTemplate>
            </asp:TemplateField>
        </Columns>
        </asp:GridView>

Aspx.cs Page:

using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.IO;
using System.Web.UI.HtmlControls;

SqlConnection con = newSqlConnection(ConfigurationManager.ConnectionStrings["connection"].ToString());
    DataTable dt;

  protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Bindgrid();
        }
    }
    public void Bindgrid()
    {
        try
        {
            SqlDataAdapter adp = new SqlDataAdapter("Select * from Employee", con);
            dt = new DataTable();
            adp.Fill(dt);
            Grd_Employee.DataSource = dt;
            Grd_Employee.DataBind();
        }
        catch (Exception ex)
        {
        }
    }

protected void Grd_Employee_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            HiddenField hf = (HiddenField)e.Row.FindControl("HiddenField1");          
                HtmlImage image = (HtmlImage)e.Row.FindControl("fileImage");
                image.Attributes.Add("src", GetIconForFile(hf.Value));

        }
    }

    private string GetIconForFile(string fileText)
    {
        string extension = Path.GetExtension(fileText);
        extension = extension.Trim('.').ToLower();
        return "~/fileicons/" + extension + ".png";
    }


0 comments:

Post a Comment