How to maintain file upload values in session while editing and updating Gridview

BeUnique 2,112 Reputation points
2024-06-03T19:51:45.72+00:00

I have developed and discussed a lot about the file upload and we were maintaining the upload file in session and data table

I used session for time being for gridview footer and emptydata template.

i want the same logic have to be implement for gridview editing and updating.

Below is my code and it is working for Footer Template and empty data template and tell me what properties I need to use to get the find gridvie control as discussed below...

My question is, How to retain the file upload values into session variable in gridview edit an update when i select dropdown values in gridview....?

Note : i am planning to use data table for maintaining file upload values in gridview and this is already in process (already posted and got reply for that). for the short demo to end user, i have to use session..

 <EditItemTemplate>
     <asp:UpdatePanel runat="server" ID="Updpanel1" UpdateMode="Always">
           <ContentTemplate>
                <asp:Label ID="lblEditCityName" Visible="false" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "City") %>'></asp:Label>
                      <asp:DropDownList ID="ddlCity" Width="100px" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlCity_SelectedIndexChanged">
                      </asp:DropDownList>
 	            <asp:TextBox ID="txtAnotherCity" Text='<%#DataBinder.Eval(Container.DataItem, "CityAnother") %>' runat="server" Visible="false"></asp:TextBox>
          </ContentTemplate>
     	<Triggers>
              <asp:AsyncPostBackTrigger ControlID="ddlCity" EventName="SelectedIndexChanged" />
     	</Triggers>
     </asp:UpdatePanel>
</EditItemTemplate>

 <asp:TemplateField ItemStyle-HorizontalAlign="Center">
                                <HeaderTemplate>
                                    <label style="text-align: center; display: block;">File Upload</label>
                                </HeaderTemplate>
                                <ItemTemplate>
                                </ItemTemplate>
                                <EditItemTemplate>
                                    <asp:FileUpload ID="fuUpload" runat="server" />
                                    <asp:Label ID="ImageErrorLabel" runat="server" />
                                    <asp:Button ID="btnUpload" Text="Upload" OnClick="Upload" runat="server" Style="display: none" />
                                </EditItemTemplate>
                            </asp:TemplateField>
if (!IsPostBack)
 { 
      FileUpload fuUpload = null;
                        if (gvcustomer.FooterRow != null)
                        {
                            control = gvcustomer.FooterRow;                            
			    DropDownList1 = (control.FindControl("ddlcity") as DropDownList);
                        }
                        else
                        {
                            control = gvcustomer.Controls[0].Controls[0];
                            DropDownList1 = (control.FindControl("ddlcity") as DropDownList);
                        }
                        fuUpload = (FileUpload)control.FindControl("fuUpload");
                        fuUpload.Attributes["onchange"] = "UploadFile(this)";
 
}
if (this.IsPostBack)
            {
                if (gvcustomer.FooterRow != null)
                {
                    control = gvcustomer.FooterRow;
                }
                else
                {
                    control = gvcustomer.Controls[0].Controls[0];
                }
                Label label = (control.FindControl("ImageErrorLabel") as Label);
                FileUpload fuUpload = (FileUpload)control.FindControl("fuUpload");
                if (Session["FileUpload1"] == null && fuUpload.HasFile)
                {
                    Session["FileUpload1"] = fuUpload.PostedFile;
                    label.Text = Path.GetFileName(fuUpload.PostedFile.FileName);
                }
                else if (Session["FileUpload1"] != null && (!fuUpload.HasFile))
                {
                    HttpPostedFile file = (HttpPostedFile)Session["FileUpload1"];
                    label.Text = Path.GetFileName(file.FileName);
                }
                else if (fuUpload.HasFile)
                {
                    Session["FileUpload1"] = fuUpload.PostedFile;
                    label.Text = Path.GetFileName(fuUpload.PostedFile.FileName);
                }
            }
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,410 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,623 questions
{count} votes

Accepted answer
  1. Lan Huang-MSFT 28,831 Reputation points Microsoft Vendor
    2024-06-04T06:36:47.34+00:00

    Hi @Gani_tpt,

    The edit row cannot be obtained directly. Perhaps you can try to record EditIndex through Session and assign a value in OnRowDataBound.

    Session["EditIndex"] = gvCustomers.EditIndex;

    protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
    {           
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if ((e.Row.RowState & DataControlRowState.Edit) > 0)
            {
                DropDownList DropDownList1 = (e.Row.FindControl("ddlCustomers") as DropDownList);
                List<Item> items = new List<Item>();
                items.Add(new Item() { Value = "1", Text = "USA" });
                items.Add(new Item() { Value = "2", Text = "UK" });
                items.Add(new Item() { Value = "3", Text = "AUS" });
                items.Add(new Item() { Value = "4", Text = "OTHERS" });
                DropDownList1.DataSource = items;
                DropDownList1.DataTextField = "Text";
                DropDownList1.DataValueField = "Value";
                DropDownList1.DataBind();
                DropDownList1.Items.Insert(0, new ListItem("--Select --", "0"));
                DataRowView dr = e.Row.DataItem as DataRowView;
                ////ddList.SelectedItem.Text = dr["category_name"].ToString();
                //ddList.SelectedValue = dr["category_name"].ToString();
                FileUpload fuUpload = (FileUpload)e.Row.FindControl("fuUpload");
                fuUpload.Attributes["onchange"] = "UploadFile(this)";
                Label label = (e.Row.FindControl("ImageErrorLabel") as Label);
                if (Session["FileUpload1"] != null)
                {
                    HttpPostedFile file = (HttpPostedFile)Session["FileUpload1"];
                    label.Text = Path.GetFileName(file.FileName);
                }
                Session["EditIndex"] = gvCustomers.EditIndex;
            }
        }
    }
    
    Control control = null;
    if (gvCustomers.FooterRow != null && (Convert.ToInt32(Session["EditIndex"]) < 0 || Session["EditIndex"] == null))
    {
        control = gvCustomers.FooterRow;
    }
    else if (Session["EditIndex"] != null && Convert.ToInt32(Session["EditIndex"]) >= 0)
    {
        control = gvCustomers.Rows[Convert.ToInt32(Session["EditIndex"])];
    }
    else
    {
        control = gvCustomers.Controls[0].Controls[0];
    }
    

    All test code:

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
        <script type="text/javascript">
            function UploadFile(fileUpload) {
                if (fileUpload.value != '') {
                    $("[id*=gvCustomers]").find("[id*=btnUpload]").click();
                }
            }
        </script>
        <script type="text/javascript">
            function checkNumberAndDecimal(val) {
                var allowedString = /^\d+(\.\d{0,2})?$/; // Allow 2 decimal place with numeric value
                if (allowedString.test(val) == false) {
                    alert("Allow 2 decimal place with numeric value...! " + val);
                    $("[id*=gvCustomers]").find("[id*=txtPayAmount]").value = "";
                    $("[id*=gvCustomers]").find("[id*=txtPayAmount]").focus();
                    return false;
                }
            }
        </script>
    </head>
    <body>
        <form id="form1" runat="server">
            <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
            <asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false" ShowFooter="true"
                OnRowEditing="OnRowEditing" OnRowCancelingEdit="OnRowCancelingEdit" OnRowUpdating="OnRowUpdating"
                OnRowDeleting="OnRowDeleting" OnRowDataBound="OnRowDataBound">
                <Columns>
                    <asp:TemplateField ItemStyle-HorizontalAlign="Center">
                        <FooterTemplate>
                            <asp:DropDownList ID="ddlCustomers" Width="100px" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlCustomers_SelectedIndexChanged">
                            </asp:DropDownList>
                            <asp:TextBox ID="txtOtherCustomers" Text="" runat="server" Visible="false"></asp:TextBox>
                        </FooterTemplate>
                        <EditItemTemplate>
                            <asp:DropDownList ID="ddlCustomers" Width="100px" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlCustomers_SelectedIndexChanged">
                            </asp:DropDownList>
                            <asp:TextBox ID="txtOtherCustomers" Text="" runat="server" Visible="false"></asp:TextBox>
                        </EditItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Name">
                        <ItemTemplate>
                            <%# Eval("Name") %>
                        </ItemTemplate>
                        <FooterTemplate>
                            <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
                        </FooterTemplate>
                        <EditItemTemplate>
                            <asp:TextBox ID="txtName" runat="server" Text='<%# Eval("Name") %>'></asp:TextBox>
                        </EditItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Country">
                        <ItemTemplate>
                            <%# Eval("Country") %>
                        </ItemTemplate>
                        <FooterTemplate>
                            <asp:TextBox ID="txtCountry" runat="server" onkeyup="return checkNumberAndDecimal(this.value)"></asp:TextBox>
                        </FooterTemplate>
                        <EditItemTemplate>
                            <asp:TextBox ID="txtCountry" runat="server" Text='<%# Eval("Country") %>'></asp:TextBox>
                        </EditItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="DOB">
                        <ItemTemplate>
                        </ItemTemplate>
                        <FooterTemplate>
                            <div>
                                <asp:TextBox ID="txtDOB" runat="server" Text=""></asp:TextBox>
                                <ajaxToolkit:CalendarExtender ID="CalendarExtender1" runat="server" TargetControlID="txtDOB"
                                    Format="MM/dd/yyyy" PopupButtonID="btnDate1"
                                    PopupPosition="BottomRight" CssClass="cal_Theme1"></ajaxToolkit:CalendarExtender>
                                <asp:ImageButton ID="btnDate1" ImageUrl="~/images/imgCalendar.png"
                                    runat="server" />
                            </div>
                        </FooterTemplate>
                        <EditItemTemplate>
                            <asp:TextBox ID="txtDOB" runat="server" Text=""></asp:TextBox>
                            <ajaxToolkit:CalendarExtender ID="CalendarExtender1" runat="server" TargetControlID="txtDOB"
                                Format="MM/dd/yyyy" PopupButtonID="btnDate1"
                                PopupPosition="BottomRight" CssClass="cal_Theme1"></ajaxToolkit:CalendarExtender>
                            <asp:ImageButton ID="btnDate1" ImageUrl="~/images/imgCalendar.png"
                                runat="server" />
                        </EditItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Upload">
                        <ItemTemplate>
                            <%# Eval("FileName") %>
                        </ItemTemplate>
                        <FooterTemplate>
                            <asp:FileUpload ID="fuUpload" runat="server" />
                            <asp:Label ID="ImageErrorLabel" runat="server" />
                            <asp:Button ID="btnUpload" Text="Upload" OnClick="Upload" runat="server" Style="display: none" />
                        </FooterTemplate>
                        <EditItemTemplate>
                            <asp:FileUpload ID="fuUpload" runat="server" />
                            <asp:Label ID="ImageErrorLabel" runat="server" Text='<%# Eval("FileName") %>' />
                            <asp:Button ID="btnUpload" Text="Upload" OnClick="Upload" runat="server" Style="display: none" />
                        </EditItemTemplate>
                    </asp:TemplateField>
                    <asp:CommandField ButtonType="Link" ShowEditButton="true" ShowDeleteButton="true"
                        ItemStyle-Width="150" />
                </Columns>
                <EmptyDataTemplate>
                    <tr>
                        <th scope="col">Customer Name</th>
                        <th scope="col">Name</th>
                        <th scope="col">Country</th>
                        <th scope="col">DOB</th>
                        <th scope="col">Upload</th>
                        <th scope="col"></th>
                    </tr>
                    <tr>
                        <td>
                            <asp:DropDownList ID="ddlCustomers" Width="100px" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlCustomers_SelectedIndexChanged">
                            </asp:DropDownList>
                            <asp:TextBox ID="txtOtherCustomers" Text="" runat="server" Visible="false"></asp:TextBox>
                        </td>
                        <td>
                            <asp:TextBox ID="txtName" runat="server" /></td>
                        <td>
                            <asp:TextBox ID="txtCountry" runat="server" onkeyup="return checkNumberAndDecimal(this.value)"></asp:TextBox>
                        </td>
                        <td>
                            <asp:TextBox ID="txtDOB" CssClass="txtInput" runat="server" Text=""></asp:TextBox>
                            <ajaxToolkit:CalendarExtender ID="CalendarExtender1" runat="server" TargetControlID="txtDOB"
                                Format="MM/dd/yyyy" PopupButtonID="btnDate1"
                                PopupPosition="BottomRight" CssClass="cal_Theme1"></ajaxToolkit:CalendarExtender>
                            <asp:ImageButton ID="btnDate1" ImageUrl="~/images/imgCalendar.png"
                                runat="server" />
                        </td>
                        <td>
                            <asp:FileUpload ID="fuUpload" runat="server" />
                            <asp:Label ID="ImageErrorLabel" runat="server" />
                            <asp:Button ID="btnUpload" Text="Upload" OnClick="Upload" runat="server" Style="display: none" />
                        </td>
                    </tr>
                </EmptyDataTemplate>
            </asp:GridView>
            <table>
                <tr>
                    <td>
                        <asp:Button ID="btnAdd" runat="server" Text="Add" OnClick="Add" />
                    </td>
                </tr>
            </table>
        </form>
    </body>
    </html>
    
     protected void Page_Load(object sender, EventArgs e)
     {
         Control control = null;
         if (!this.IsPostBack)
         {
             this.BindGrid();
             if (gvCustomers.FooterRow != null && (Convert.ToInt32(Session["EditIndex"]) < 0 || Session["EditIndex"] == null))
             {
                 control = gvCustomers.FooterRow;
             }
             else if (Session["EditIndex"] != null && Convert.ToInt32(Session["EditIndex"]) >= 0)
             {
                 control = gvCustomers.Rows[Convert.ToInt32(Session["EditIndex"])];
             }
             else
             {
                 control = gvCustomers.Controls[0].Controls[0];
             }
             TextBox txtDOB = control.FindControl("txtDOB") as TextBox;
             txtDOB.Attributes.Add("readonly", "readonly");
             FileUpload fuUpload = (FileUpload)control.FindControl("fuUpload");
             fuUpload.Attributes["onchange"] = "UploadFile(this)";
             DropDownList DropDownList1 = (control.FindControl("ddlCustomers") as DropDownList);
             List<Item> items = new List<Item>();
             items.Add(new Item() { Value = "1", Text = "USA" });
             items.Add(new Item() { Value = "2", Text = "UK" });
             items.Add(new Item() { Value = "3", Text = "AUS" });
             items.Add(new Item() { Value = "4", Text = "OTHERS" });
             DropDownList1.DataSource = items;
             DropDownList1.DataTextField = "Text";
             DropDownList1.DataValueField = "Value";
             DropDownList1.DataBind();
             DropDownList1.Items.Insert(0, new ListItem("--Select --", "0"));
         }
         if (this.IsPostBack)
         {
             if (gvCustomers.FooterRow != null && (Convert.ToInt32(Session["EditIndex"]) < 0 || Session["EditIndex"] == null))
             {
                 control = gvCustomers.FooterRow;
             }
             else if (Session["EditIndex"] != null && Convert.ToInt32(Session["EditIndex"]) >= 0)
             {
                 control = gvCustomers.Rows[Convert.ToInt32(Session["EditIndex"])];
             }
             else
             {
                 control = gvCustomers.Controls[0].Controls[0];
             }
             Label label = (control.FindControl("ImageErrorLabel") as Label);
             FileUpload fuUpload = (FileUpload)control.FindControl("fuUpload");
             if (Session["FileUpload1"] == null && fuUpload.HasFile)
             {
                 Session["FileUpload1"] = fuUpload.PostedFile;
                 label.Text = Path.GetFileName(fuUpload.PostedFile.FileName);
             }
             else if (Session["FileUpload1"] != null && (fuUpload.PostedFile.ContentLength < 0))
             {
                 HttpPostedFile file = (HttpPostedFile)Session["FileUpload1"];
                 label.Text = Path.GetFileName(file.FileName);
             }
             else if (fuUpload.HasFile)
             {
                 Session["FileUpload1"] = fuUpload.PostedFile;
                 label.Text = Path.GetFileName(fuUpload.PostedFile.FileName);
             }               
         }
     }
     protected void OnRowEditing(object sender, GridViewEditEventArgs e)
     {
         gvCustomers.EditIndex = e.NewEditIndex;
         this.BindGrid();
     }
     protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
     {           
         if (e.Row.RowType == DataControlRowType.DataRow)
         {
             if ((e.Row.RowState & DataControlRowState.Edit) > 0)
             {
                 DropDownList DropDownList1 = (e.Row.FindControl("ddlCustomers") as DropDownList);
                 List<Item> items = new List<Item>();
                 items.Add(new Item() { Value = "1", Text = "USA" });
                 items.Add(new Item() { Value = "2", Text = "UK" });
                 items.Add(new Item() { Value = "3", Text = "AUS" });
                 items.Add(new Item() { Value = "4", Text = "OTHERS" });
                 DropDownList1.DataSource = items;
                 DropDownList1.DataTextField = "Text";
                 DropDownList1.DataValueField = "Value";
                 DropDownList1.DataBind();
                 DropDownList1.Items.Insert(0, new ListItem("--Select --", "0"));
                 DataRowView dr = e.Row.DataItem as DataRowView;
                 ////ddList.SelectedItem.Text = dr["category_name"].ToString();
                 //ddList.SelectedValue = dr["category_name"].ToString();
                 FileUpload fuUpload = (FileUpload)e.Row.FindControl("fuUpload");
                 fuUpload.Attributes["onchange"] = "UploadFile(this)";
                 Label label = (e.Row.FindControl("ImageErrorLabel") as Label);
                 if (Session["FileUpload1"] != null)
                 {
                     HttpPostedFile file = (HttpPostedFile)Session["FileUpload1"];
                     label.Text = Path.GetFileName(file.FileName);
                 }
                 Session["EditIndex"] = gvCustomers.EditIndex;
             }
         }
     }
     protected void OnRowUpdating(object sender, GridViewUpdateEventArgs e)
     {
         gvCustomers.EditIndex = -1;
         this.BindGrid();
     }
     protected void OnRowCancelingEdit(object sender, EventArgs e)
     {
         gvCustomers.EditIndex = -1;
         this.BindGrid();
     }
     protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e)
     {
     }
     protected void Upload(object sender, EventArgs e)
     {
         Control control = null;
         if (gvCustomers.FooterRow != null && (Convert.ToInt32(Session["EditIndex"]) < 0 || Session["EditIndex"] == null))
         {
             control = gvCustomers.FooterRow;
         }
         else if (Session["EditIndex"] != null && Convert.ToInt32(Session["EditIndex"]) >= 0)
         {
             control = gvCustomers.Rows[Convert.ToInt32(Session["EditIndex"])];
         }
         else
         {
             control = gvCustomers.Controls[0].Controls[0];
         }
         Label label = (control.FindControl("ImageErrorLabel") as Label);
         FileUpload fuUpload = (FileUpload)control.FindControl("fuUpload");
         if (Session["FileUpload1"] == null && fuUpload.HasFile)
         {
             Session["FileUpload1"] = fuUpload.PostedFile;
             label.Text = Path.GetFileName(fuUpload.PostedFile.FileName);
             HttpPostedFile file = (HttpPostedFile)Session["FileUpload1"];
             SaveFile(file);
         }
         else if (Session["FileUpload1"] != null && (fuUpload.PostedFile.ContentLength <0))
         {
             HttpPostedFile file = (HttpPostedFile)Session["FileUpload1"];
             label.Text = Path.GetFileName(file.FileName);
             SaveFile(file);
         }
         else if (fuUpload.HasFile)
         {
             Session["FileUpload1"] = fuUpload.PostedFile;
             label.Text = Path.GetFileName(fuUpload.PostedFile.FileName);
             SaveFile(fuUpload.PostedFile);
         }
     }
     private void SaveFile(HttpPostedFile file)
     {
         string fname = Path.GetFileName(file.FileName);
         file.SaveAs(Server.MapPath("~/images/" + fname));
     }
     private void BindGrid()
     {
         string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
         string query = "SELECT Name, Country,FileName FROM Customers";
         using (SqlConnection con = new SqlConnection(constr))
         {
             using (SqlCommand cmd = new SqlCommand(query, con))
             {
                 using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
                 {
                     using (DataTable dt = new DataTable())
                     {
                         sda.Fill(dt);
                         con.Open();
                         gvCustomers.DataSource = dt;
                         gvCustomers.DataBind();
                         con.Close();
                     }
                 }
             }
         }
     }
     protected void ddlCustomers_SelectedIndexChanged(object sender, EventArgs e)
     {
         Control control = null;
         if (gvCustomers.FooterRow != null && (Convert.ToInt32(Session["EditIndex"]) < 0 || Session["EditIndex"] == null))
         {
             control = gvCustomers.FooterRow;
         }
         else if (Session["EditIndex"] != null && Convert.ToInt32(Session["EditIndex"]) >= 0)
         {
             control = gvCustomers.Rows[Convert.ToInt32(Session["EditIndex"])];
         }
         else
         {
             control = gvCustomers.Controls[0].Controls[0];
         }
         DropDownList ddlCustomers = (control.FindControl("ddlCustomers") as DropDownList);
         TextBox txtOtherCustomers = control.FindControl("txtOtherCustomers") as TextBox;
         if (ddlCustomers.SelectedItem.Text == "OTHERS")
         {
             txtOtherCustomers.Visible = true;
         }
         else
         {
             txtOtherCustomers.Visible = false;
         }
     }
     public class Item
     {
         public Item() { }
         public string Value { set; get; }
         public string Text { set; get; }
     }
     protected void Add(object sender, EventArgs e)
     {
         Control control = null;
         if (gvCustomers.FooterRow != null)
         {
             control = gvCustomers.FooterRow;
         }
         else if (gvCustomers.EditIndex >= 0)
         {
             control = gvCustomers.Rows[gvCustomers.EditIndex];
         }
         else
         {
             control = gvCustomers.Controls[0].Controls[0];
         }
         string name = (control.FindControl("txtName") as TextBox).Text;
         string country = (control.FindControl("txtCountry") as TextBox).Text;
         string txtDOB = (control.FindControl("txtDOB") as TextBox).Text;
         HttpPostedFile file = (HttpPostedFile)Session["FileUpload1"];
         string filename = Path.GetFileName(file.FileName);
         byte[] bytes = null;
         if (file != null)
         {
             BinaryReader br = new BinaryReader(file.InputStream);
             bytes = br.ReadBytes((int)file.InputStream.Length);
         }
         string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
         string query = "INSERT INTO Customers VALUES(@Name, @Country,@FileName,@Data,@Data1)";
         using (SqlConnection con = new SqlConnection(constr))
         {
             using (SqlCommand cmd = new SqlCommand(query, con))
             {
                 cmd.Parameters.AddWithValue("@Name", name);
                 cmd.Parameters.AddWithValue("@Country", country);
                 cmd.Parameters.AddWithValue("@FileName", filename);
                 cmd.Parameters.AddWithValue("@Data", bytes);
                 cmd.Parameters.AddWithValue("@Data1", bytes);
                 con.Open();
                 cmd.ExecuteNonQuery();
                 con.Close();
             }
         }
         Response.Redirect(Request.Url.AbsoluteUri);
     }
    

    Best regards,
    Lan Huang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. AgaveJoe 27,656 Reputation points
    2024-06-04T12:54:41.81+00:00

    The FileUpload buffer is destroyed when the request ends which includes the HttpPostedFile. In other words, the HttpPostedFile stream cannot persist between post backs due to fundamentally how the Server Control works. It seems like you are not testing the code.

    As suggested in your previous thread(s), read the file stream into a byte array. The byte array can be stored in Session and persist between post back.

    protected void Submit_Click(object sender, EventArgs e)
    {            
        Stream myStream = MyFile.FileContent;
        Byte[] buff = new Byte[MyFile.PostedFile.ContentLength];
        myStream.Read(buff, 0, MyFile.PostedFile.ContentLength);
        Session["FileBuffer"] = buff;
        Session["FileName"] = MyFile.FileName;
    }
    protected void TestSession_Click(object sender, EventArgs e)
    {
        Byte[] buff = (byte[])Session["FileBuffer"];
        string fileName = (string)Session["FileName"];
        string filePath = Server.MapPath($"~/images/{fileName}") ;
        using (var fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
        {
            fs.Write(buff, 0, buff.Length);
        }
    }
    

    Keep in mind, Session will not work if the web application is load balanced.