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 条评论
登录 后参与评论

相关文章

来自专栏菩提树下的杨过

Silverlight Telerik控件学习:TreeView数据绑定并初始化选中状态、PanelBar的Accordion效果、TabPanel、Frame基本使用

实际开发中控件的数据源肯定是动态绑定的,不可能在xaml里写死item项。既然要绑定,就先来几个实体类: ? 上面是类图,各类的代码如下:  Business...

31780
来自专栏linux驱动个人学习

高通msm8909耳机调试

1、DTS相应修改: DTS相关代码:kernel/arch/arm/boot/dts/qcom/msm8909-qrd-skuc.dtsi: 1 s...

1.2K50
来自专栏SAP最佳业务实践

SAP S/4 HANA新变化-CO物料帐(for Ver.1610)

Material Ledger Actual Costing has been activated already in the system before t...

97750
来自专栏计算机视觉与深度学习基础

Leetcode 236. Lowest Common Ancestor of a Binary Tree

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes i...

21190
来自专栏calvin

SignalR主动通知订阅者示例

关键点:GlobalHost.ConnectionManager.GetHubContext

18930
来自专栏游戏杂谈

CURLcode的定义

http://curl.haxx.se/libcurl/c/libcurl-errors.html

44920
来自专栏c#开发者

在DataGrid中选择,确认,删除多行复选框列表

在DataGrid中选择,确认,删除多行复选框列表 Selecting, Confirming & Deleting Mul...

38970
来自专栏沃趣科技

Oracle 12c系列(九) | 通过unplug与plug方式升级pdb数据库

对于Oracle数据库升级操作,每个版本之间的升级步骤均相似,首先升级Oracle软件,然后升级数据库内的数据字典表。

32530
来自专栏PPV课数据科学社区

【学习】七天搞定SAS(三):基本模块调用

搞定基本的函数之后,开始鼓捣SAS里面的模型。也就是说,要开始写PROC了。说实话,越学SAS,越觉得SAS像Stata...无论是从输出的样式,还是语法。好不...

35450
来自专栏算法+

3D Lut 电影级调色算法 附完整C代码

长话短说,3d lut(全称 : 3D Lookup table )它是通过建立一个颜色映射表,对图像的色调进行重调的算法。

1.1K100

扫码关注云+社区

领取腾讯云代金券