专栏首页c#开发者Add a FileUpload control to your GridView [转]

Add a FileUpload control to your GridView [转]

Add a FileUpload control to your GridView

Category:  ASP.Net 2.0 In this post I’m going to show you how you can add the FileUpload control to a GridView control, and how to save the uploaded file, both on disc and to your data source. Note: In this post I decided to use the SqlDataSource, only for making the example in this post small and easy to understand. 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>

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • XML Encryption in .Net

    XML Encryption in .Net One of the new features being introduced with the Whidbey...

    阿新
  • 解决:TF30170: Microsoft.ProjectCreationWizard.WorkItemTracking

    Error TF30170: The plugin Microsoft.ProjectCreationWizard.WorkItemTracking fail...

    阿新
  • Selecting multiple checkboxes inside a GridView control

    Introduction GridView is a new data bound control introduced by Microsoft in Vis...

    阿新
  • PAT (Advanced Level) Practice 1096 Consecutive Factors (20 分)

    Among all the factors of a positive integer N, there may exist several consecuti...

    glm233
  • 2018-10-28 String.valueOf(null) 会报空指针异常

    https://stackoverflow.com/questions/4042675/why-string-valueofnull-is-causing-nu...

    Albert陈凯
  • SAP最佳业务实践:SD–带变式价格的销售报价(663)-4创建订单

    一、 VA01 Deriving Order from Follow-On Quotation Aftercomparing various quotation...

    SAP最佳业务实践
  • NumPy 实现梯形法积分

    用户2183996
  • 2019.8.15乘兴打Codeforces Round #569 (Div. 2)小记

    Recently, on the course of algorithms and data structures, Valeriy learned how t...

    glm233
  • The Note based on Data Structures and Algorithm Analysis in C CHAPTER 3 P1

    The Note based on Data Structures and Algorithm Analysis in C

    Chiptune
  • 什么是SAP物料主数据里的Batch

    Materials are produced and theoretically have the same properties. Nevertheless ...

    Jerry Wang

扫码关注云+社区

领取腾讯云代金券