【问题标题】:How to download a file from a specific row in GridView如何从 GridView 中的特定行下载文件
【发布时间】:2020-01-27 06:41:36
【问题描述】:

我需要一些帮助来下载我 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();
}

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

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

谢谢

【问题讨论】:

    标签: c# asp.net gridview


    【解决方案1】:

    正是因为这条线

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

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

    <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"
    

    【讨论】:

    • 您好,感谢您的回复。我已经根据您的建议更新了我的问题,但是当我点击下载按钮时,现在什么也没有发生?
    • 啊!现在有意义,但我收到此错误:System.InvalidCastException: 'Unable to cast object of type 'System.Int32' to type 'System.String'.' 在这一行 string val = (string)this.GridView1.DataKeys[rowIndex]["id"];
    • 再次检查更新的答案,无需将任何内容转换为字符串然后转换为 int。
    • 太棒了!感谢您的解释!现在一切正常!!!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-07
    • 1970-01-01
    • 1970-01-01
    • 2013-09-28
    • 1970-01-01
    • 2016-01-17
    相关资源
    最近更新 更多