Solved

Need button to programmatically add controls to a page

Posted on 2010-11-18
13
1,019 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
  • 5
  • 3
  • 2
  • +2
13 Comments
 
LVL 51

Expert Comment

by:HainKurt
Comment Utility
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
Comment Utility
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 500 total points
Comment Utility
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
 

Author Comment

by:asphaltninja
Comment Utility
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
Comment Utility
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
Comment Utility
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
What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

 
LVL 51

Expert Comment

by:HainKurt
Comment Utility
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
Comment Utility
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
Comment Utility
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 500 total points
Comment Utility
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
Comment Utility
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
Comment Utility
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

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

ASP.Net to Oracle Connectivity Recently I had to develop an ASP.NET application connecting to an Oracle database.As I am doing it first time ,I had to solve several problems. This article will help to such developers  to develop an ASP.NET client…
Introduction This article shows how to use the open source plupload control to upload multiple images. The images are resized on the client side before uploading and the upload is done in chunks. Background I had to provide a way for user…
This video discusses moving either the default database or any database to a new volume.
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.

762 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

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now