?
Solved

Need button to programmatically add controls to a page

Posted on 2010-11-18
13
Medium Priority
?
1,028 Views
Last Modified: 2012-05-10
So I have a button on my page which I'd like to add a few textboxes and a fileupload control when clicked. It only works the first time the user clicks the button. Here's the code. Note: "pnlContainer" refers to an asp panel that's already on the page in markup.
       protected void addFileUploader(object sender, System.EventArgs e)
        {
            int cnt = Convert.ToInt32(Session["cnt"]);
            String codeBox = "txtCode" + cnt;
            String versionBox = "txtVersion" + cnt;
            String keywordBox = "txtKeyword" + cnt;
            String uploader = "fUp" + cnt;
            TextBox txtCode = new TextBox();
            txtCode.ID = codeBox;
            txtCode.Width = Unit.Pixel(70);
            pnlContainer.Controls.Add(txtCode);
            pnlContainer.Controls.Add(new LiteralControl(" "));
            TextBox txtVersion = new TextBox();
            txtVersion.ID = versionBox;
            txtVersion.Width = Unit.Pixel(70);
            pnlContainer.Controls.Add(txtVersion);
            pnlContainer.Controls.Add(new LiteralControl(" "));
            TextBox txtKeyword = new TextBox();
            txtKeyword.Width = Unit.Pixel(70);
            txtKeyword.ID = keywordBox;
            pnlContainer.Controls.Add(txtKeyword);
            pnlContainer.Controls.Add(new LiteralControl("<br/>"));
            FileUpload fup = new FileUpload();
            fUp.ID = uploader;
            pnlContainer.Controls.Add(fup);
            pnlContainer.Controls.Add(new LiteralControl("<br/>"));
            cnt++;
            pnlContainer.DataBind();
        }  

Open in new window

0
Comment
Question by:asphaltninja
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 3
  • 2
  • +2
13 Comments
 
LVL 57

Expert Comment

by:HainKurt
ID: 34164762
could not get the logic here... you have only one pnlContainer on your page I guess and each time you are adding to this panel? are you clearing the controls each time? if you dont clear, you should get multiple controls on panel... also I dont see how this sub is called from button click... are you using some repeater? how many "add" button do you have on your page? do you have a link to share? also can you please post the aspx code and also button_click code...
0
 
LVL 7

Expert Comment

by:Ironhoofs
ID: 34164811
I think you forgot to update the session variable.

line 27:  cnt++;

should probably read something like:

Session["cnt"] = Convert.ToString(cnt++);
0
 
LVL 16

Accepted Solution

by:
Swapnil Piparia earned 2000 total points
ID: 34164824
Hi asphaltninja,

         ASP.Net file upload control looses his state when postback happen, so when you perform server click, everytime file upload control gone away and new one is added in place of that and you always see one file upload control at a time.

         To resolve this you have to use javascript to create new file upload control everytime.

         Please follow below steps to implement it.
         1. Add Snippet ID=1940097 (attached with this message) in your aspx page.
         2. Also add script tag from Snippet ID=1940174 in your aspx page.
         3. When you click on "Upload Files" or upload button in your application, you will get collection of Files by with "Request.Files" which you can use to upload file / show information like file size and extension.
                  Dim uploadFilCol As HttpFileCollection = Request.Files

Thanks,
NetSwap.
<script type="text/javascript">   
    function addFileUploadBox() {   
        if (!document.getElementById || !document.createElement)   
            return false;   
  
        var uploadArea = document.getElementById("upload-area");   
  
        if (!uploadArea)   
            return;   
  
        var newLine = document.createElement("br");   
        uploadArea.appendChild(newLine);   
  
        var newUploadBox = document.createElement("input");   
  
        // Set up the new input for file uploads   
        newUploadBox.type = "file";   
        newUploadBox.size = "60";   
  
        // The new box needs a name and an ID   
        if (!addFileUploadBox.lastAssignedId)   
            addFileUploadBox.lastAssignedId = 100;   
  
        newUploadBox.setAttribute("id", "dynamic" + addFileUploadBox.lastAssignedId);   
        newUploadBox.setAttribute("name", "dynamic:" + addFileUploadBox.lastAssignedId);   
        uploadArea.appendChild(newUploadBox);   
        addFileUploadBox.lastAssignedId++;   
    }   
</script>

Open in new window

<div align="center" style="overflow:auto; height:250px" >
    <asp:Literal ID="lblInfo" runat="server" meta:resourcekey="lblInfoResource1"></asp:Literal>
    <p id="upload-area">
        <input id="File1" type="file" runat="server" size="60" />
    </p>
    <input type="hidden" runat="server" id="hdnDirName" value="" />
>
</div>
<div align="center">
    
     <asp:Button ID="btnUpload" CssClass="buttons" runat="server" Text="Upload Files"
        OnClick="btnUpload_Click" />
    <input type="button" id="btnAddNew1" runat="server" class="buttons" onclick="addFileUploadBox();"
        value="Add File" />
</div>

Open in new window

0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:asphaltninja
ID: 34164908
hello netswap and thanks for your help. How would I also be able to have new texboxes appear when the button is clicked?
0
 
LVL 16

Expert Comment

by:Swapnil Piparia
ID: 34165023
Hi asphaltninja,

          You can add additional textbox in same way, file upload control is added in javascript.
 
          Below is the code snippet you can use.

var newUploadBox = document.createElement("input");  
uploadArea.appendChild(newUploadBox);
newUploadBox.setAttribute("id", "txt" + addFileUploadBox.lastAssignedId);  
newUploadBox.setAttribute("name", "txt:" + addFileUploadBox.lastAssignedId);  
       

Thanks,
netswap.
0
 

Author Comment

by:asphaltninja
ID: 34165025
HainKurt

"could not get the logic here... you have only one pnlContainer on your page I guess and each time you are adding to this panel? are you clearing the controls each time? if you dont clear, you should get multiple controls on panel... also I dont see how this sub is called from button click... are you using some repeater? how many "add" button do you have on your page? do you have a link to share? also can you please post the aspx code and also button_click code..."

The "addFileUploader" is handling the button click event. Yes I have only one asp:panel named "pnlContainer" on the page. I'm not clearing the controls each time Here's the markup:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Individual.aspx.cs" MasterPageFile="~/core.Master" Inherits="fileSystemLoader.Individual" %>

<asp:Content ContentPlaceHolderID="headContent" runat="server">Individual Upload Page</asp:Content>

<asp:Content ContentPlaceHolderID="mainContent" runat="server">
<div>
<span style="color:red;">Press the "Add" button to include more files.</span>
</div>
<asp:Panel ID="pnlContainer" runat="server">
<asp:TextBox ID="txtCode" runat="server" HoveredStyle-BackColor="Yellow" Width="70px"/>&nbsp;<asp:TextBox runat="server" HoveredStyle-BackColor="Yellow" ID="txtVersion" Width="70px"/>
&nbsp;<asp:TextBox ID="txtKeyword" runat="server" HoveredStyle-BackColor="Yellow" Width="70px"/><br />
<asp:FileUpload ID="fUp" runat="server" Font-Names="Verdana"/><br />
</asp:Panel>
<asp:Button ID="btnAdd" Text="Add" runat="server" OnClick="addFileUploader"/>
<asp:Button ID="btnSubmit" runat="server" OnClick="btnSubmit_Click" Text="Upload" Font-Names="Verdana"/>
</asp:Content>

Open in new window

0
 
LVL 57

Expert Comment

by:HainKurt
ID: 34165108
did you do this

Session["cnt"] = Convert.ToString(cnt++);

(suggested by Ironhoofs)  also

are you setting Session["cnt"] = "1" on page_load?
0
 

Author Comment

by:asphaltninja
ID: 34165182
yes, I added the Session["cnt"] = Convert.ToString(cnt++);
and I set the session variable in page_load as so:
if(!this.isPostBack){
Session["cnt"] = 1;

}
should it not be inside the postback loop?
0
 

Author Comment

by:asphaltninja
ID: 34166109
Okay netswap, your method appears to be working. I can retrieve the values for the files, but how to i retrieve the values from the texboxes?
0
 
LVL 16

Assisted Solution

by:Swapnil Piparia
Swapnil Piparia earned 2000 total points
ID: 34171738
Hi asphaltninja,

        What are the values you are storing in textbox?
        For File related information as I have mentioned above, you can retrieve it with " Dim uploadFilCol As HttpFileCollection = Request.Files" by Request.Files collection.

Thanks,
NetSwap.
0
 

Author Comment

by:asphaltninja
ID: 34172012
hi netswap,

the values in the text inputs are additional values that will eventually go into a database with the file, like keyword tags.
0
 
LVL 29

Expert Comment

by:Kumaraswamy R
ID: 34387735
This question has been classified as abandoned and is being closed as part of the Cleanup Program.  See my comment at the end of the question for more details.
0

Featured Post

On Demand Webinar: Networking for the Cloud Era

Did you know SD-WANs can improve network connectivity? Check out this webinar to learn how an SD-WAN simplified, one-click tool can help you migrate and manage data in the cloud.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Problem Hi all,    While many today have fast Internet connection, there are many still who do not, or are connecting through devices with a slower connect, so light web pages and fast load times are still popular.    If your ASP.NET page …
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
In this video we outline the Physical Segments view of NetCrunch network monitor. By following this brief how-to video, you will be able to learn how NetCrunch visualizes your network, how granular is the information collected, as well as where to f…
NetCrunch network monitor is a highly extensive platform for network monitoring and alert generation. In this video you'll see a live demo of NetCrunch with most notable features explained in a walk-through manner. You'll also get to know the philos…
Suggested Courses

752 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question