Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » ASP.NET & Web Forms » Uploading Multiple Files in ASP.NET 2.0: Part II

Uploading Multiple Files in ASP.NET 2.0: Part II

In ASP.NET 2.0, the FileUpload control enables the users to upload the files from your web pages. Here, I am going to show you, "how can you upload multiple file on a single button click in ASP.NET 2.0." Here, in the same article I am adding one more functionality, i.e. the user can get the right to upload any number of images by clicking on Add button.

Author Rank:
Total page views :  6951
Total downloads :  333
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
MakeMultipleUpload.zip
 
Powerful ASP.NET Hosting w/ NO Setup Fees. Click Here!
Become a Sponsor


MindCracker Jobs


In ASP.NET 2.0, the FileUpload control enables the users to upload files from web pages. The FileUpload control consists of a text box and a browse button. A click on the button allows the users to select a file on the client and upload it to the server. Here, I am representing a functionality to provide a right to the user to upload any number of images.

Let us start with uploading multiple files on a single button click. 

Follow these 2 steps:
 

Here is the aspx code:

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

 

<!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>Make Multiple Upload Images</title>

 

    <script type="text/javascript" language="javascript">               

         function DecreaseRow(rowNo)

        {

            var hid = document.getElementById('<%= hidCurRow.ClientID %>');

            hid.value = rowNo;

        }

        function IncreseRows()

        {

            var hid = document.getElementById('<%= hidCurRow.ClientID %>');

            hid.value = "";

        }

        function SetZero()

        {

            var hid = document.getElementById('<%= hidCurRow.ClientID %>');

            hid.value = "0";

        }

    </script>

 

</head>

<body>

    <form id="form1" runat="server">

        <table cellpadding="0" cellspacing="0" width="80%" align="center">

            <tr>

                <td>

                    <asp:Table ID="tblMin" runat="server">

                        <asp:TableHeaderRow>

                            <asp:TableHeaderCell>

                        File

                            </asp:TableHeaderCell>

                            <asp:TableHeaderCell>

                        Remove

                            </asp:TableHeaderCell>

                        </asp:TableHeaderRow>

                        <asp:TableRow>

                            <asp:TableCell>

                                <asp:FileUpload ID="fu1" runat="server" />

                            </asp:TableCell>

                            <asp:TableHeaderCell>

                                <asp:Button ID="btn1" runat="server" Text="Remove" OnClientClick="return DecreaseRow('1');" />

                            </asp:TableHeaderCell>

                        </asp:TableRow>

                    </asp:Table>

                    <asp:Button ID="btnAdd" runat="server" OnClick="btnAdd_Click" Text="Add" OnClientClick="return IncreseRows();" />

                    <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click"

                        OnClientClick="SetZero();" /><br />

                    <asp:HiddenField ID="hidMax" runat="server" Value="1" />

                    <asp:HiddenField ID="hidRow" runat="server" Value="1" />

                    <asp:HiddenField ID="hidCurRow" runat="server" />

                </td>

            </tr>

        </table>

    </form>

</body>

</html>

This is the cs code:


using
System;

using System.Data;

using System.Configuration;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using System.IO;

 

public partial class _Default : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

        if (Page.IsPostBack == true)

        {

            AddRows();

        }

    }

    private void AddRows()

    {

        try

        {

            if (hidCurRow.Value != "" && hidCurRow.Value != "0")

            {

                DecreaseCount();

            }

            else if (hidCurRow.Value == "")

            {

                IncreaseCount();

            }

 

            for (int count = 1; count < tblMin.Rows.Count; count++)

            {

                tblMin.Rows.RemoveAt(1);

            }

 

            int maxRows = Convert.ToInt32(hidMax.Value);

            string[] arrRows = hidRow.Value.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

            for (int count = 1; count <= maxRows; count++)

            {

                Boolean isAdd = false;

                for (int incount = 0; incount < arrRows.Length; incount++)

                {

                    if (arrRows[incount] == count.ToString())

                    {

                        isAdd = true;

                        break;

                    }

                }

 

                if (isAdd == true)

                {

                    TableRow tr = new TableRow();

 

                    TableCell tcfu = new TableCell();

                    FileUpload fup = new FileUpload();

                    fup.ID = "fu" + count.ToString();

                    tcfu.Controls.Add(fup);

 

                    TableCell tcbtn = new TableCell();

                    Button bt = new Button();

                    bt.ID = "btn" + count.ToString();

                    bt.Text = "Remove";

                    bt.Attributes.Add("onclick", "DecreaseRow('" + count.ToString() + "');");

                    tcbtn.Controls.Add(bt);

                    tr.Cells.Add(tcfu);

                    tr.Cells.Add(tcbtn);

                    tblMin.Rows.Add(tr);

                }

            }

        }

        catch

        {

        }

    }

 

    private void IncreaseCount()

    {

        string strVal = hidMax.Value;

        if (strVal != "")

        {

            int iMax = Convert.ToInt32(strVal);

            iMax = iMax + 1;

            hidMax.Value = iMax.ToString();

 

            if (hidRow.Value != "")

            {

                hidRow.Value = hidRow.Value + "," + iMax.ToString();

            }

            else

            {

                hidRow.Value = iMax.ToString();

            }

        }

    }

 

    private void DecreaseCount()

    {

        string strCurRow = hidCurRow.Value;

        string[] arrRows = hidRow.Value.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

        hidRow.Value = "";

        for (int count = 0; count < arrRows.Length; count++)

        {

            if (arrRows[count] != strCurRow)

            {

                if (hidRow.Value == "")

                {

                    hidRow.Value = arrRows[count];

                }

                else

                {

                    hidRow.Value = hidRow.Value + "," + arrRows[count];

                }

            }

        }

    }

 

    protected void btnAdd_Click(object sender, EventArgs e)

    {

 

    }

 

    protected void btnSubmit_Click(object sender, EventArgs e)

    {

        if (hidRow.Value != "")

        {

            string[] strVal = hidRow.Value.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

            for (int count = 0; count < strVal.Length; count++)

            {

                FileUpload fup = new FileUpload();

                fup = (FileUpload)tblMin.FindControl("fu" + strVal[count]);

                if (fup != null)

                {

                    if (fup.PostedFile != null && fup.FileName != "")

                    {

                        fup.SaveAs(Server.MapPath("MyFiles") + "\\" + Path.GetFileName(fup.FileName));

                    }

                }

            }

        }

    }

}

 

When, we run the Apllication, result will be:

Upload1.JPG

Image 1.

Here, user can add many upload controls by clicking on Add button and even he can remove the upload controls by clicking on Remove button.

Upload2.JPG

Image 2.


Login to add your contents and source code to this article
 About the author
 
Rahul Kumar Saxena
Rahul shows great interests in working with Microsoft technologies. He specializes in the implementation of DataBase & Graphics. His area of expertise includes: C#, ASP.NET,ADO.NET,Windows Forms & Web Services. He hails from background , Master's in Computer Application.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
MakeMultipleUpload.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Powerful ASP.NET Hosting w/ NO Setup Fees. Click Here!
Become a Sponsor
 Comments
Hi Rahul by kalpana On March 31, 2009
I really like Ur article,its nice
Reply | Email | Delete | Modify | 
Re: Hi Rahul by Rahul Kumar On April 3, 2009
Thanx KALPANA
Reply | Email | Delete | Modify | 
tips for making website more impressive by hitesh On April 1, 2009
Hi, I m doing my last year project in visual studio using c#. its a website. I m unable to make it impressive pl help me with how to make more impressive and code also pl
Reply | Email | Delete | Modify | 
Re: tips for making website more impressive by Rahul Kumar On April 3, 2009
Hi hitesh,
H R U

Which type of website u r making
Reply | Email | Delete | Modify | 
The code doesn't work by Hector On April 7, 2009
Hi, i wrote the code in a page in my site, it works fine, but when I selected som file with one of the fileuploaders and try to delete or add a new item, the page stop working and show me an error "Internet Explorer can not display the page". Another question, why do you always delete the row #1? if I have something selected it will be lost. Thanks. Hector
Reply | Email | Delete | Modify | 
Really nice article by prachi On April 17, 2009
Hey, It worked absolutely fine but there is one problem that when i fill one textbox with browse button and THEN click add button ,then it deletes context of the previous feilds like earlier file filled is gone. Any solution for that?
Reply | Email | Delete | Modify | 
thanks by danny On October 16, 2009
very helpful article, thanks!

---------------------------------
Danny, Los Angeles Locksmith
Reply | Email | Delete | Modify | 
Implementation of Fileupload controls in multilayerarchitecture by Santhosha On November 14, 2009

hi

Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 1999 - 2010  Mindcracker LLC. All Rights Reserved