Solved

Need button to programmatically add controls to a page

Posted on 2010-11-18
13
1,022 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
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 500 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
Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 

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 51

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 500 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

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
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…
Two types of users will appreciate AOMEI Backupper Pro: 1 - Those with PCIe drives (and haven't found cloning software that works on them). 2 - Those who want a fast clone of their boot drive (no re-boots needed) and it can clone your drive wh…
Although Jacob Bernoulli (1654-1705) has been credited as the creator of "Binomial Distribution Table", Gottfried Leibniz (1646-1716) did his dissertation on the subject in 1666; Leibniz you may recall is the co-inventor of "Calculus" and beat Isaac…

856 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