zoukankan      html  css  js  c++  java
  • 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>

    In the 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;
    }
    }
  • 相关阅读:
    面试-23种设计模式
    面试-类和对象的区别
    面试-链表和数组的区别
    Python强制抛出自定义异常
    Python中模拟C# Linq的一些操作
    python随机数seed用法
    Python目录常用操作
    Unity编辑器下获取动画的根运动状态并修改
    python字符串操作,以及对应的C#实现
    测试-一个unity的编译bug,初始化器
  • 原文地址:https://www.cnblogs.com/neozhu/p/1202588.html
Copyright © 2011-2022 走看看