Showing posts with label Use File Upload Control inside Update Panel in ASP. Net C#. Show all posts
Showing posts with label Use File Upload Control inside Update Panel in ASP. Net C#. Show all posts

Thursday, July 7, 2016

How to use file upload control in asp.net with update panel

In this article, I am going to explain how to use file upload control inside update panel in asp.net c#. Create a folder with name "Upload" for saving your file at solution explorer.

aspx code

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="UploadFileInsideUpdatePanel.aspx.cs" Inherits="UploadFileInsideUpdatePanel" %>
 
<!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>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="smain" runat="server"></asp:ScriptManager>
    <asp:UpdatePanel ID="upmain" runat="server">
    <ContentTemplate>
    <fieldset>
    <legend>Upload File Inside Update Panel</legend>
    <asp:FileUpload ID="flupload" runat="server" />
    <asp:Button ID="bthUplaod" runat="server" Text="Save" onclick="bthUplaod_Click" />
    <asp:Label ID="lblmsg" runat="server" ForeColor="Green"></asp:Label>
    </fieldset>
    </ContentTemplate>
    <Triggers>
    <asp:PostBackTrigger ControlID="bthUplaod" />
    </Triggers>
    </asp:UpdatePanel>
    </form>
</body>
</html>

aspx.cs code

using System;
using System.IO;
 
public partial class UploadFileInsideUpdatePanel : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
 
    }
    protected void bthUplaod_Click(object sender, EventArgs e)
    {
        try
        {
            lblmsg.Text = string.Empty;
            if (flupload.HasFile)
            {
                string physicalDirPath = Server.MapPath("~/Upload");
                string filedata = Path.GetFileNameWithoutExtension(flupload.FileName) + Guid.NewGuid() + Path.GetExtension(flupload.FileName);
                string filename = physicalDirPath + "\\" + filedata;
                flupload.SaveAs(filename);
                lblmsg.Text = "Saved Successfully";
            }
        }
        catch (Exception ex)
        {
            lblmsg.Text = ex.Message;
        }
    }
}

Output: