Home » .Net FrameworkRSS

GridView and FileUpload control and EditItemTemplate

Is it possible to place a FileUpload control inside the EditItemTemplate of a GridView control?  How do I access this control in the GridView_RowUpdating event in order to save the uploaded file to the file system?  I can't use the e.Row.FindControl() method like I can in the GridView_RowDataBound event.
Thanks
 

11 Answers Found

 

Answer 1

 I have the same problem...

 

Answer 2

 http://fredrik.nsquared2.com/viewpost.aspx?PostID=292

 

Answer 3

I have applied this method for using the FileUpload but when the code behind runs the .HasFile attribute always returns false and the .FileName returns an empty string. Has anyone ever had this problem?

 

protected void lnkBtnEditUploadDone_Click(object sender, EventArgs e)
        {
            //File Upload === not workingint index = Convert.ToInt16(((LinkButton)sender).CommandArgument);
            FileUpload uploadControl = gdApprovals.Rows[index].FindControl("uploadCorrected") as FileUpload;

            if (uploadControl.HasFile)
            {
                uploadControl.SaveAs(Server.MapPath("~/Assignment_Repo/") + uploadControl.FileName);
            }
        }
 ** ps: have tried inserting the code into the Row_Updating and Row_Command but encountered the same problem
 

Answer 4

The fact that it is inside EditItemTemplate means you are editing so the most likely place is at RowUpdating which is the final destination before the grid commits the changes to the database.  RowUpdating was meant for business validation allowing you to abort updates simply by issuing ==> e.Cancel = true  In your case don't do this simply execute your filesave opertion and let it go on it's marry way.

 

 

Answer 5

Try this

protectedvoid GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)

{

FileUpload FileUpload1 = (FileUpload)GridView1.Rows[e.RowIndex].FindControl("FileUpload1");

}

 

Answer 6

 This works for me.  One problem,  on edit old values in parameter get changed to null.

ASP 3.5 page 

In Gridview on the page           

<asp:TemplateField HeaderText="File Attachment" sortExpression="strFileAttachment">
                <ItemTemplate>
                    <p>
                        <%#Eval("strFileAttachment")%>
                    </p>
                </ItemTemplate>

                <EditItemTemplate>
                    <asp:FileUpload ID="FileUploadFileAttachment" FileName='<%# Bind("strFileAttachment") %>'    runat="server" />
                    Current File: <%#Eval("strFileAttachment")%>
                </EditItemTemplate>

</asp:TemplateField>

 

In VB code - 

Private Sub GridView1_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles GridView1.RowUpdating

        Dim fFileAttachment As FileUpload = CType(Me.GridView1.Rows(e.RowIndex).FindControl("FileUploadFileAttachment"), FileUpload)
     
        If fFileAttachment.HasFile Then
            Dim path As String = Server.MapPath("../img/ads/" + fFileAttachment.FileName)
            ' grant Write permission to the ASP.NET process account
            ' for the Images subdirectory.
            fFileAttachment.SaveAs(path)
        End If
 
End Sub

 

 

 

Answer 7

Hi

try this example:

To add a FileUpload control  to your GridView, you first need to add an ItemTemplateField. To the template field you can add both an ItemTemplate, which will be displayed when the row is not in edit mode, and an EditItemTemplate, which will be displayed when the row is in edit mode. If you only want to show the FileUpload control when a row has entered edit mode, you can add the FileUpload ot the EditItemTemplate:

 

<asp:TemplateField HeaderText="Image">

    <ItemTemplate>

       <asp:Image ImageUrl="<%# Eval("Image") %>" runat="server" ID="image" />

    </ItemTemplate>

    <EditItemTemplate>

       <asp:FileUpload ID="FileUpload1" runat="server" />

    </EditItemTemplate>

</asp:TemplateField>

 

As you can see in the code above, the ItemTempalte will display an Image control, where the ImageUrl attribute of the control is bound to a “Image” field (The “Image” in this case is the name of the data source’s column that will contain the path to the image that should be displayed).

 

To pass the filename that is uploaded by the FileUpload control to your data-source control’s UpdateCommand, you need to create a parameter for the filename. To create a parameter that will be used by your UpdateCommand, you can add the parameter to the data-source’s UpdateParameters collection. The following is an example of a SqlDataSource control where an Image parameter is added, and where the Select- and UpdateCommand are specified (The Image parameter represents the filename that will be passed to the UpdateCommnad):

 

<asp:SqlDataSource ConnectionString="<%$ ConnectionStrings:CustomerConnectionString %>"

   ID="SqlDataSource1" runat="server"

   SelectCommand="SELECT [CustomerID], [Name], [Image] FROM [Customers]"

   UpdateCommand="UPDATE [Customers] SET [Name] = @Name, [Image] = @Image WHERE [CustomerID] = @original_CustomerID">

   <UpdateParameters>

     <asp:Parameter Name="Image" DefaultValue="default.gif" />

   </UpdateParameters>

</asp:SqlDataSource>

 

The FileUpload control, will not automatically save the uploaded file. To save the file you need to use the FileUpload control’s SaveAs method. Before you can use the SaveAs method you need to get the instance of the FileUpload control for the row you are editing. To get the instance of the control you can hook up to the GridView’s RowUpdating event. The following code will get the instance of the FileUpload control and save the uploaded file:

 

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)

{

    FileUpload fileUpload = GridView1.Rows[e.RowIndex].FindControl("FileUpload1") as FileUpload;

 

    fileUpload.SaveAs(System.IO.Path.Combine(Server.MapPath("Images"), fileUpload.FileName));

 

    SqlDataSource1.UpdateParameters["Image"].DefaultValue = "~/Images/" + fileUpload.FileName;

}

 

From the RowUpdating event’s GridViewUpdateEventArgs, you can get the index of GridView’s row that is going to be updated. You can use the RowIndex property to get the row you are editing from the GridView’s Rows collection. When you have the instance of the GirdView’s row, you can use the FindControl method to locate the FileUpload control. In the RowUpdating event the Image parameter added to the UpdateParamters collection will be set to the name of the uploaded file. The RowUpdating event will be trigged before the data-source control’s UpdateCommand is executed, so the RowUpdateing event is a good place to change the value of the data-source parameters that will be passed to the data-source’s UpdateCommand.

 

When the data-source update command is executed, the name of the uploaded file will be passed to your UpdateCommand, and the uploaded file will be saved to your disc.

 

The following is an example where the FileUpload control is added to the GridView:

 

<%@ Page Language="C#" AutoEventWireup="true"  %>

 

<script runat="server">

 

   protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)

   {

      FileUpload fileUpload = GridView1.Rows[e.RowIndex]. FindControl("FileUpload1") as FileUpload;

 

      fileUpload.SaveAs(System.IO.Path.Combine("C:\\", fileUpload.FileName));

 

      SqlDataSource1.UpdateParameters["Image"].DefaultValue = fileUpload.FileName;

   }

</script>

 

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

    <title>Untitled Page</title>

</head>

<body>

   <form id="form1" runat="server">

   <div>

      <asp:GridView AutoGenerateColumns="False" DataKeyNames="CustomerID" DataSourceID="SqlDataSource1" ID="GridView1" runat="server" OnRowUpdating="GridView1_RowUpdating">

          <Columns>

             <asp:CommandField ShowEditButton="True"></asp:CommandField>

             <asp:BoundField DataField="CustomerID" HeaderText="CustomerID" InsertVisible="False" ReadOnly="True" SortExpression="CustomerID"></asp:BoundField>

             <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name"></asp:BoundField>

             <asp:TemplateField HeaderText="Image">

                <ItemTemplate>

                   <asp:Image ImageUrl="<%# Eval("Image") %>" runat="server" ID="image" />

                 </ItemTemplate>

                 <EditItemTemplate>

                    <asp:FileUpload ID="FileUpload1" runat="server" />

                 </EditItemTemplate>

             </asp:TemplateField>

           </Columns>

        </asp:GridView>

        <asp:SqlDataSource ConnectionString="<%$ ConnectionStrings:CustomerConnectionString %>"

            ID="SqlDataSource1" runat="server"

            SelectCommand="SELECT [CustomerID], [Name], [Image] FROM [Customers]"

            UpdateCommand="UPDATE [Customers] SET [Name] = @Name, [Image] = @Image WHERE [CustomerID] = @original_CustomerID">

        <UpdateParameters>

            <asp:Parameter Name="Image" DefaultValue="default.gif" />

        </UpdateParameters>

        </asp:SqlDataSource>

    </div>

    </form>

</body>

</html>

Good Luck

 

Answer 8

 HI Yasserzaid,

I still have the issue of once the user clicks the edit row the fileupload  control comes up with a blank textbox.  If the user doesn't enter a filename and then clicks update the old filename is blanked out. I would like to keep the old value if the user doesn't enter a new value. 

I've tried not updating the parameter with an if then like this:

If fFileAttachment.HasFile Then
            Dim path As String = Server.MapPath("../img/ads/" + fFileAttachment.FileName)
            fFileAttachment.SaveAs(path)
            SqlDataSource1.UpdateParameters("strFileAttachment").DefaultValue = fFileAttachment.FileName
        Else
 
            'In this section I've tried code like e.newvalue  = e.oldvalue  but I get Nothing for the old value.
        End If

 The old filename still gets wiped out if a user doesn't enter a new value.  Do you have the same issue?  Any ideas?

 

 

Answer 9

Try this: 

At the edit template you can store the old file name inside a label.

<EditItemTemplate>

<asp:FileUpload ID="newFile" runat="server"  />
<asp:label ID="oldFile" runat="server" text='<%# Eval("portada") %>' Visible="false"  />


 </EditItemTemplate>

We put the oldFile label property visible="false", so our editTemplate looks nice and clean.

The on updating the grdView we check if the fileUpload has actually a file, if so, we use the new filename, if not we use the value stored at the label. Like this:

Private Sub updateGrid(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles rptNoticias.RowUpdating
        Dim newFile As FileUpload = CType(Me.rptNoticias.Rows(e.RowIndex).FindControl("newFile"), FileUpload)
        Dim oldFile As label = CType(Me.rptNoticias.Rows(e.RowIndex).findControl("oldFile"), label)
       
         If newFile.HasFile Then
            newFile.SaveAs(Server.MapPath("../fotos/portadas/") & upPortada.fileName)
            myDs.UpdateParameters("fileName").DefaultValue = newFile.fileName
        Else
            myDs.UpdateParameters("fileName").DefaultValue = oldFile.text
        End If
    End Sub

Hope this helps...

 

Answer 10

Hello yaseerzaid,

Thanks u solved my problem of past two weeks, but in this code

SqlDataSource1.UpdateParameters["path"].DefaultValue = "~\\App_Upload\\" + fu.FIleName;

The Image is getting uploaded in the folder App_Uploads but in table the path is same as like ~\App_Uploads\img.jpg the actual path is not showing how may I acheive this ???
 

 

Answer 11

I think you should put an FileUploder into the GridView, and say that you should get the specific file through its text, and use File.GetAllBytes to get its image bytes and assign it to the SqlDataSource (UpdateCommand). Exeucte it manually and re-databind to the GridView, let's get started:

<asp:TemplateField HeaderText="Image">

    <ItemTemplate>

       <asp:Image ImageUrl="<%# Eval("Image") %>" runat="server" ID="image" />

    </ItemTemplate>

    <EditItemTemplate>

       <asp:FileUpload ID="FileUpload1" runat="server" />

    </EditItemTemplate>

</asp:TemplateField>

<asp:SqlDataSource ConnectionString="<%$ ConnectionStrings:CustomerConnectionString %>"

   ID="SqlDataSource1" runat="server"

   SelectCommand="SELECT [CustomerID], [Name], [Image] FROM [Customers]"

   UpdateCommand="UPDATE [Customers] SET [Name] = @Name, [Image] = @Image WHERE [CustomerID] = @original_CustomerID">

   <UpdateParameters>

     <asp:Parameter Name="Image" Type="Object" />

   </UpdateParameters>

</asp:SqlDataSource>

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)

{

    FileUpload fileUpload = GridView1.Rows[e.RowIndex].FindControl("FileUpload1") as FileUpload;

 

    string path = System.IO.Path.Combine(Server.MapPath("Images"), fileUpload.FileName));

 

    SqlDataSource1.UpdateParameters["Image"].DefaultValue = File.ReadAllBytes(path);

   

}


 

 
 
 

<< Previous      Next >>


Microsoft   |   Windows   |   Visual Studio   |   Follow us on Twitter