GridView绑定链接,点击链接下载

点滴积累,点滴进步~

前段时间,做网站遇到这样的需求,先整理如下。如有什么不妥的地方,还请各位仁兄赐教。尤其到现在,对于手动添加序号的原理还不甚明了,望明白的朋友稍作解释。e.Row.Cells[i]是指向???   先行谢过~

1. 前台代码

其中,第一列是为了为数据添加序号。第二列为链接Report列,若果Report从数据库中读取出来的数据为空,则没有DownloadReport显示;若不为空,点击Download Report下载链接文件。

<asp:GridView ID="grdTest" runat="server" AutoGenerateColumns="False" CellPadding="4"DataKeyNames="TestID" GridLines="None" OnRowDataBound="grdTest_RowDataBound">
<RowStyle BackColor="#EFF3FB" HorizontalAlign="Left" />
<Columns>
<asp:BoundField DataField="TestName" HeaderText="No.">
<HeaderStyle Width="80px" />
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lbtnView" runat="server" CommandArgument='<%#Eval("ReportLink") %>'
Text='<%#Eval("ReportLink")!=""?"Download Report":""%>' OnCommand="lbtnView_Command"></asp:LinkButton>
</ItemTemplate>
<HeaderTemplate>
<asp:Literal ID="Literal1" runat="server" Text="ReportLink"></asp:Literal>
</HeaderTemplate>
<ItemStyle HorizontalAlign="Center" Width="120px" />
</asp:TemplateField>
</Columns>
</asp:GridView>

2. 后台代码.

下载链接,是绑定模板列,通过LinkButton的CommandArgument传递所绑定的值。在LinkButton的OnCommand事件中,实现下载功能。

protected void lbtnView_Command(object sender, CommandEventArgs e)
{
try
{
string fullName = e.CommandArgument.ToString();
//fullName = @"\\MyComputer\Downloads\911_04-07.xls";
string fileName = System.IO.Path.GetFileName(fullName);
if (!string.IsNullOrEmpty(fullName))
{
FileInfo downloadFile = new FileInfo(fullName);
if (downloadFile.Exists)
{
Response.Clear();
Response.ClearHeaders();
Response.Buffer = false;
Response.ContentType = "application/octet-stream";
Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));//downloadFile.FullName
Response.AppendHeader("Content-Length", downloadFile.Length.ToString());
Response.WriteFile(downloadFile.FullName);
Response.Flush();
Response.End();
}
}
else
{
ClientScript.RegisterStartupScript(this.GetType(), "", "alert('Report Link is not Exist !');", true);
}
}
catch
{

ClientScript.RegisterStartupScript(this.GetType(), "", "alert('Error,Please report administrator!);", true);
}
}


//手动为GridView最前面添加序列号
protected void grdTest_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowIndex >= 0)
{
e.Row.Cells[0].Text = Convert.ToString(e.Row.DataItemIndex + 1);
}
}

 

posted @ 2011-11-22 12:53  eva.xiao  阅读(1473)  评论(0编辑  收藏  举报