繁体   English   中英

如何从GridView中的特定行下载文件

[英]How to download a file from a specific row in GridView

我需要一些帮助来下载GridView特定行中的文件。

这是我的GridView标记代码:

 <asp:GridView ID="GridView1" runat="server" 
                       AutoGenerateColumns="False"
                       DataKeyNames="id" 
                       CssClass="mydatagrid" 
                       Width="550px" 
                       BackColor="#DEBA84" 
                       BorderColor="#DEBA84" 
                       BorderStyle="None" 
                       BorderWidth="1px" 
                       CellPadding="3" 
                       CellSpacing="2" 
                       AllowSorting="true">
                    <Columns>
                          <asp:BoundField DataField="filename" HeaderText="Name" />
                          <asp:BoundField DataField="datestamp" HeaderText="Date" />
                          <asp:TemplateField ShowHeader="False">
                        <ItemTemplate>
                         <asp:Button ID="Button1" runat="server" 
                                            Text="Download" 
                                            ControlStyle-CssClass="btn btn-success" 
                                            CommandName="MyCommand" CommandArgument='<%# DataBinder.Eval(Container, "RowIndex") %>'/>
                                    </ItemTemplate>
             </asp:TemplateField>
          </Columns>
      <FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
      <HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" width="250px" />
      <PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
      <RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
      <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
      <SortedAscendingCellStyle BackColor="#FFF1D4" />
      <SortedAscendingHeaderStyle BackColor="#B95C30" />
      <SortedDescendingCellStyle BackColor="#F1E5CE" />
      <SortedDescendingHeaderStyle BackColor="#93451F" />
  </asp:GridView>

然后下载我有的文件:

 protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName.Equals("MyCommand"))
    {
        int rowIndex = int.Parse(e.CommandArgument.ToString());
        string val = (string)this.GridView1.DataKeys[rowIndex]["id"];
        string strQuery = "SELECT filename, filecontent, datestamp FROM FileTable where id=@id";
        SqlCommand cmd = new SqlCommand(strQuery);
        cmd.Parameters.Add("@id", SqlDbType.Int).Value = 1;
        DataTable dt = GetData(cmd);
        if (dt != null)
        {
            download(dt);
        }
    }
}
private DataTable GetData(SqlCommand cmd)
{
    DataTable dt = new DataTable();
    String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
    SqlConnection con = new SqlConnection(strConnString);
    SqlDataAdapter sda = new SqlDataAdapter();
    cmd.CommandType = CommandType.Text;
    cmd.Connection = con;
    try
    {
        con.Open();
        sda.SelectCommand = cmd;
        sda.Fill(dt);
        return dt;
    }
    catch
    {
        return null;
    }
    finally
    {
        con.Close();
        sda.Dispose();
        con.Dispose();
    }
}
private void download (DataTable dt)
{
    Byte[] bytes = (Byte[])dt.Rows[0]["filecontent"];
    Response.Buffer = true;
    Response.Charset = "";
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    Response.ContentType = dt.Rows[0]["filecontent"].ToString();
    Response.AddHeader("content-disposition", "attachment;filename="
    + dt.Rows[0]["filename"].ToString());
    Response.BinaryWrite(bytes);
    Response.Flush(); 
    Response.End();
}

所以现在发生的事情是,当我点击下载时,它总是下载第一行的文件,而不是我点击下载的行。

我知道我需要指定我点击了哪一行才能下载文件,但不确定如何完成它?

谢谢

正是因为这条线

cmd.Parameters.Add("@id", SqlDbType.Int).Value = 1;

然后您需要从 onclick 更改为 grid 命令:

<asp:TemplateField>
    <ItemTemplate>
        <asp:Button ID="Button1" runat="server"Text="Download" 
                      ControlStyle-CssClass="btn btn-success" CommandName="MyCommand" CommandArgument='<%# DataBinder.Eval(Container, "RowIndex") %>'
    </ItemTemplate>
</asp:TemplateField>

而在你后面的代码中

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if(e.CommandName.Equals("MyCommand"))
    {
        int rowIndex = int.Parse(e.CommandArgument.ToString());
        string val = (string)this.grid.DataKeys[rowIndex]["id"];
        // you can run your query here
    }
}

在你的情况下:

 protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName.Equals("MyCommand"))
    {
        int rowIndex = int.Parse(e.CommandArgument.ToString());
        var val = this.GridView1.DataKeys[rowIndex]["id"];
        string strQuery = "SELECT filename, filecontent, datestamp FROM FileTable where id=@id";
        SqlCommand cmd = new SqlCommand(strQuery);
        cmd.Parameters.Add("@id", SqlDbType.Int).Value = val;
        DataTable dt = GetData(cmd);
        if (dt != null)
        {
            download(dt);
        }
    }
}

您还需要将onrowcommand="ContactsGridView_RowCommand"到您的 Gridview

<asp:GridView ID="GridView1" runat="server" onrowcommand="ContactsGridView_RowCommand"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM