Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Need button to programmatically add controls to a page

Posted on 2010-11-18
13
Medium Priority
?
1,032 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 60

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
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 

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 60

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

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

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

IntroductionWhile developing web applications, a single page might contain many regions and each region might contain many number of controls with the capability to perform  postback. Many times you might need to perform some action on an ASP.NET po…
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
Sometimes it takes a new vantage point, apart from our everyday security practices, to truly see our Active Directory (AD) vulnerabilities. We get used to implementing the same techniques and checking the same areas for a breach. This pattern can re…
In this video, Percona Solution Engineer Rick Golba discuss how (and why) you implement high availability in a database environment. To discuss how Percona Consulting can help with your design and architecture needs for your database and infrastr…
Suggested Courses

604 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