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> |
Selecting
event handler of the ObjectDataSource, you can get the binary data of the uploaded image from the FileUpload control, then set it to the select parameter in the InputParameters
collection:protected void ObjectDataSource1_Inserting(object sender, ObjectDataSourceMethodEventArgs e)
{
FileUpload upload = DetailsView1.FindControl("FileUpload") as FileUpload;
using (BinaryReader reader = new BinaryReader(upload.PostedFile.InputStream))
{
byte[] bytes = new byte[upload.PostedFile.ContentLength];
reader.Read(bytes, 0, bytes.Length);
e.InputParameters["imgData"] = bytes;
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix