Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FileUpload upload codebehind.

How can i upload with FileUpload codebehind only? My controls are made codebehind because i have Dropdown_SelectedIndexChanged and need to generate various numbers of controls. I can list the controls fine and attach file and text to txtbox with:

        private void SetChildrenCountControls(int total)
        {
          for (int i = 0; i < total; i++)
          {
            var tbBirthDate = new TextBox();
            tbBirthDate.ID = "tbBirthDate_" + (i + 1);
            tbBirthDate.CssClass = "tbSister_input";
            tbBirthDate.EnableViewState = true;

            FileUpload upload = new FileUpload();
            upload.ID = "imgUpload_" + (i + 1);
            upload.CssClass = "tbSister_upload";
            upload.EnableViewState = true;

            ChildrenCountTextPanel.Controls.Add(tbBirthDate);
            ChildrenCountTextPanel.Controls.Add(upload);
          }
       }    

And can get the enterede text in the txtbox with:

         protected void lbFamilySave_Click(object sender, EventArgs e)
    {
        var countSisters = ChildrenCountTextPanel.Controls.OfType<TextBox>();
        string sisterBirth = string.Empty;
        foreach (var sister in countSisters)
        {
            if (sister.ID.Contains("tbBirthDate_"))
                sisterBirth = sister.Text;
        }
    } 

How can i get the file from the FileUpload controls? Cant seem to do above with FileUpload.

like image 701
paradise_lost Avatar asked Jun 12 '26 13:06

paradise_lost


1 Answers

In the click event below you are getting TextBoxes and not FileUpload Control

btn_protected void lbFamilySave_Click(object sender, EventArgs e)
{
        var countSisters = ChildrenCountTextPanel.Controls.OfType<TextBox>();

A file upload control is of this type System.Web.UI.WebControls.FileUpload

So please get the FileUpload control then do the following:

if (myFileUpload.HasFile)
{
  string savePath = @"C:\Temp\" + myFileUpload.FileName;

  myFileUpload.SaveAs(savePath);
}
like image 158
HatSoft Avatar answered Jun 14 '26 01:06

HatSoft



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!