Solved

Need button to programmatically add controls to a page

Posted on 2010-11-18
13
1,025 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 55

Expert Comment

by:Huseyin KAHRAMAN
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
SharePoint Admin?

Enable Your Employees To Focus On The Core With Intuitive Onscreen Guidance That is With You At The Moment of Need.

 

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 55

Expert Comment

by:Huseyin KAHRAMAN
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

MS Dynamics Made Instantly Simpler

Make Your Microsoft Dynamics Investment Count  & Drastically Decrease Training Time by Providing Intuitive Step-By-Step WalkThru Tutorials.

Question has a verified solution.

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

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…
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
Come and listen to Percona CEO Peter Zaitsev discuss what’s new in Percona open source software, including Percona Server for MySQL (https://www.percona.com/software/mysql-database/percona-server) and MongoDB (https://www.percona.com/software/mongo-…
This is a high-level webinar that covers the history of enterprise open source database use. It addresses both the advantages companies see in using open source database technologies, as well as the fears and reservations they might have. In this…

691 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