.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
david stephan
Gaurav Pal
Post New Web Links

FileUpload control loses value on postback.

Posted By:      Posted Date: September 11, 2010    Points: 0   Category :ASP.Net
I'm having a little problem with my file uploading. Does anybody know how to maintain the value in the FileUpload control between server posts?I have a form which, among other things, uploads a file. I am using an FileUpload control (created dynamically) to let a user browse their PC for a file and then using the SaveAs method to upload the file to the server.When I'm selecting a file and Click on Next button for processing then selected file is lost.Same is happening with me with HtmlTextArea (dynamically generated) , the problem was that I was not again re-initializing the controls after postback. What I did is re-initialized it in Init method of placeholder (as I have created/placed all dynamic controls in placeholder ).But this thing is not working for fileupload control. I found solution in one of the forum is that "use hiddenField Control to transfer the selected file from the client to server"but this mechanism will only help to retain the name of file in a hidden variable and the FileUpload1.PostedFile.SaveAs(filename) will not work bcz of absense of object (fileupload1).here is code:protected void lnkbtnNext_Click(object sender, EventArgs e) { if (Session["pnl"].ToString() == "0") { /* other stuff code */ } else if (Session["pnl"].ToString() == "1")

View Complete Post

More Related Resource Links

People Picker control used in ASP.Net wizard control. Loses values on Postback?


I am using a people picker control in a custom visual web part with Visual Studio 2010, Sharepoint 2010.

The people picker control is on an asp.net wizard control.

On the wizard step with the people picker control, after postback the people picker control has selected values.

But when clicking the next or previous buttons of the wizard control, the people picker control does not retain its selected values.


Microsoft.SharePoint.WebControls.PeopleEditor pe

pe.AllowTypeIn = true;
pe.AutoPostBack = true;
pe.AllowEmpty = true;
pe.MultiSelect = false;
pe.SharePointGroup = "My SP Group Name";
pe.SelectionSet = "SPGroup";
pe.ValidatorEnabled = true;
pe.CommaSeparatedAccounts = pe.CommaSeparatedAccounts;

Any suggestions?


Server side validation of Fileupload control not working



I've tried this method in my code behind to try and validate that the Fileupload control has a file or not. I get the error message the the event "Server Validate" cannot be found. Can anyone tell why? Thanks.

Public Sub CustomValidator1_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles CustomValidator1.ServerValidate

' Get file name

        Dim uploadAvatar As FileUpload = DirectCast(AdvertisementForm.FindControl("uploadAvatar"), FileUpload)

        Dim UploadFileName As String = uploadAvatar.PostedFile.FileName

        If UploadFileName = "" Then
            ' There is no file selected
            args.IsValid = False
            Dim Extension As String = UploadFileName.Substring(UploadFileName.L

Dynamically load user control without postback


Hi all,

I need urgent help. (c#coding)

In my base page, I have a dropdownlist control which loads different usercontrols on selectedindexchanged event.

While loading these usercontrols, my page postbacks all the page. I used updatepanel but again same problem.

Is there any way to load controls without postback? I Really need help as soon as possible.

Here is my code:

protected void Page_Init(object sender, EventArgs e)
        if (Session["control"] != null)
            string c = Session["control"].ToString();
            if (c == "1")
                iuc = (IlkogretimUC)LoadControl("~/Controls/Ilkogretim.ascx");
                dl.SelectedValue = Session["control"].ToString();
            else if (c == "2")
                luc = (LiseUC)LoadControl("~/Controls/LiseUC.ascx");
                dl.SelectedValue = Session["control"].ToString();
            else if (c == "3")
                youc = (YuksekokulUC)LoadControl("~/Controls/Yuksekokul.ascx");

FileUpload Control with membership and roles


Hi Everyone!

I'm pretty new to development using Microsoft technologies.

I'm trying to build a portal kind of an application in asp.net, in which one of the functionality is letting people log in and upload their documents. The upload page is only accessible to registered users of the portal.


I would like to track the user uploaded files according to their userIds.

Is it possible to use the FileUpload Control and C# to fetch the current user id, create a directory with the same name(as that of userID) in the file system and upload the files( multiple file upload, if necessary) into it?

Also another admin page would have to be able to see the list of files uploaded by the specific user and download it if necessary.

Could anyone help me with this?

I'm also expecting alternate solutions to the problem.

Awaiting a response.

Thanks in advance 


Getting an error using FileUpload Control on a server.

Hello FriendsI m getting a problem while executing the following code for my website.This code works perfactly on localhost but when I use d same code on my webpage on the server it does nothing...even it doesnt return any error msg.Plz help me...protected void BtnUpload_Click(object sender, EventArgs e) {        int intFileSizeLimit = 1000;               string strFileNameWithPath = FileUpload1.PostedFile.FileName;               string strExtensionName = System.IO.Path.GetExtension(strFileNameWithPath);              string strFileName = System.IO.Path.GetFileName(strFileNameWithPath);           int intFileSize = FileUpload1.PostedFile.ContentLength / 1024;                              strExtensionName = strExtensionName.ToLower();        if (strExtensionName.Equals(".doc") || strExtensionName.Equals(".txt") || strExtensionName.Equals(".docx"))        {      

few questions about fileupload control

hey im currently using this to save pictures to a certin folderImgUpload.SaveAs(Server.MapPath("../Img/") + ImgUpload.FileName); my questions is 1. how do i avoid rewriting an image, in other words how do i check if there is another file using the same name? 2. how do i iterate on each image in the folder so that i can print certin html code for each img like for each image print this -> (<img src="Image_Path/Image-name.jpg/gif" width="?" height="?">   tnx

Get content of programatically created control before postback

Hi.I have quite a problem here, and hope you can help :)I´ll try to describe the problem in steps, as this might be the easiest to understand:1. Page_Load is called when the page is requested, and calls a BuildTable() method2. The BuildTable method creates a table which contains several textboxes3. the user types some text in these textboxes4. The userthen  changes an item in a Dropdownlist on the page which is intended to change some other content on the page5. Page_Load is called, and afterwards the DropDownListBookingType_SelectedIndexChanged(object sender,EventArgs e) method are called, and the content is changed6. The text the user typed in the programmatically created textbox controls are lost!Now how do I remain this text information? If just the SelectedIndex_changed method was called first, I could save it in session.. But as far as I can tell, all data on the page are discarded when you create a partial postback :(What to do?Thanks alot for your time!

Client Javascript runs, but then page errors out when clicking on a control that uses postback

Using this script on a button click <script language="javascript"> function printdiv(printpage) { var headstr = "<html><head><title></title></head><body>"; var footstr = "</body>"; var newstr = document.all.item(printpage).innerHTML; var oldstr = document.body.innerHTML; document.body.innerHTML = headstr + newstr + footstr; window.print(); document.body.innerHTML = oldstr; return false; } </script> After it is done, I can't click on my calendar control.  I was hoping to add somethign that would force a refresh in the script, but nothing I do works. Any thoughts?  Thanks! 

get disable control values during postback

 Hi, I have a page it contains some criteria part based on criteria click upon generate button data will displayed on gird page also contains modify button where user can modify the grid data once user clicks modify button the selected criteria part will disable everything works as expected.. but i am not getting the disable control values during postback how to get the values during postback?   Thanks Maverick  

How to Set default file name of image in FileUpload Control

helloi want to set  default value in Fileupload control.Because when i select file name using fileupload then save that file to sqlserver database i got problem when no file is select. so i found alternate of that i should store default image into database through fileupload control but now my query is how to set default image to fileupload control.please i want source code.i really need it......tnx in advance

unable to trace value after postback within Custom Server Control

public class TextBox : AStateManagement, IControl { #region "Variables" #region "Local Variables" protected System.Web.UI.WebControls.WebControl _TextBox = null; protected string _CssClass = string.Empty; protected string _Text = string.Empty; protected bool _Visible = true; protected bool _Enabled = true; protected string _ID = string.Empty; protected bool _IsViewStateLoaded = false; #endregion "Local Variables" #region "Global Variables" #endregion "Global Variables" #endregion "Variable" #region "Constructor" public TextBox() { _TextBox = new System.Web.UI.WebControls.TextBox(); _TextBox.ID = this.UniqueID; } #endregion "Constructor" #region "Events" #endregion "Events" #region "Disposable" #endregion "Disposable" #region "Properties" public override string CssClass { get { return _CssClass; } set { _TextBox.CssClass = _CssClass = value; } } public virtual string Text { get { return _Text; }

Replace control postback processing in ASP.NET MVC

I've developed a Web User Control with ASP.NET Web Foms that uses client side binding and allows to the user to enter a series of items. During a post, the JavaScript code of my control serializes the items in JSON and put them in a hidden field so the server code of the control can take this JSON string, deserialize it and expose the entered items through a property . How can I obtain a similar functionality and reusability with MVC since during a post my control won't be there to take this JSON string and interpret it correctly? In the end, the hidden field "trick" and the specifics of what data is serialized (and in what way) is just part of the internals of my control that shouldn't have to care to "anyone" outside it (after all, that's why the component abstraction exists). (Sorry about my English)

Get Control that triggered cross page postback

Hi I want to know if there is a way to get the control that triggered the postback,such as I have one page Page1.aspx with two buttons like<asp:Button id="btnCrossPost" runat="server" Text="Post To Another Page" PostBackUrl="Page2.aspx" CommandArgument="1"/><asp:Button id="btnCrossPost2" runat="server" Text="Post To Another Page 2" PostBackUrl="Page2.aspx" CommandArgument="2"/>and in Page2.aspx I want to get which button triggered the post back so that I can get the command argument which is vitalto the processing of the next page.Thanks.

How to determine if a user control is contained by the update panel that triggered async postback

Does anyone know a simple way to determine if a user control is contained in an update panel that was triggered for async postback?At the moment, the only pseudo logic for this I can think of is?'Loop through the update panel controls on the page and find the one that is involved in the postback (isInPartialRendering)'Try to find the user control as a child of the update panel

Find a form control that is created after postback

HiI have a drop down list (created during form design) with auto postback enabled. And I use AJAX to prevent 'visible postback'. When a user choose an item from the drop down list, the system will then perform a postback and created a set of form control's such as label, drop down list and text box for entry.Then, I will have a button (created during form design), and when I click on the button, i want to find for the form control that are created after the post back, but I cant find them!I wonder if those form controls are render to the web form?? But I have no problem finding the drop down list that is created during design time.Anyway I can find those form controls?Thank You.

Server Control - Implement Postback


Hi all,

I am writing a server control and need to implement postback. It is a simple calendar control - it renders a textbox and a button using the override of RenderContents which pops up a asp:Calendar control in a new window (written separately to the control) which sets the value of the textbox with javascript.

I just want the TextBox to keep it's value on postback. I inherit from WebControl rather than from TextBox as I thought it would be nice to have a greater level of control but if inheriting from TextBox is better practice I'd be interested instead for guidance on how to add to the render rather than overwrite it altogether (to add a button).

I'm not in the habit of writing such general questions but what I haven't been able to find is some decent resources to put me on the right path.

I've been looking at http://msdn.microsoft.com/en-us/library/aa720415(v=VS.71).aspx but can't get it working (I think I've implemented everything they say in the article, other than that I am using a different render method, but it doesn't change anything).

Does anyone have any simple examples or resources they could point me at to help?

Thanks in advance,


not retaining value of fileupload control in asp wizard control


I am developing a web application in asp.net and c#. I'm using an asp wizard control. there is  6 wizard steps in my wizard. In each phase im using many controls, so that many postback is done during execution.
I am using a asp fileupload control in second wizard step. My problem is that the value selected using fileupload control is not getting when i click wizard finsh button in the final step. values acquired using all other controls are available there.
Hope someone help me.
I just want to get the selected filename in last step. 
ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend