Image Upload using ASP.Net with C# (Practical 8)

Default.aspx

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

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
        <asp:FileUpload ID="FileUpload1" runat="server" />
        <br />
        <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
        <br />
        <br />
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
        <br />
        <br />
        <asp:GridView ID="GridView1" runat="server">
            <Columns>
                <asp:BoundField DataField="Text" />
                <asp:ImageField DataImageUrlField="Value" >
                    <ControlStyle Height="100px" Width="100px" />
                </asp:ImageField>
            </Columns>
        </asp:GridView>
   
    </div>
    </form>
</body>

</html>

Default.aspx.cs

using System;
using System.IO;
using System.Collections.Generic;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    private void loadImages()
    {
        string[] filePaths = Directory.GetFiles(Server.MapPath("~/Images/"));
        List<ListItem> files = new List<ListItem>();
        foreach (string filePath in filePaths)
        {
            string fileName = Path.GetFileName(filePath);
            files.Add(new ListItem(fileName, "~/Images/" + fileName));
        }
        GridView1.DataSource = files;
        GridView1.DataBind();
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        loadImages();
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile)
        {
            string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
            Label1.Text = fileName;
            FileUpload1.PostedFile.SaveAs(Server.MapPath("~/Images/") + fileName);
        }

        if (IsPostBack)
        {
            loadImages();
        }
    }
}


Comments

Popular posts from this blog

Zeller's Congruence

Property Event-Delegation

Method with variable arguments