这是我的问题。我有一个用户控件,它将使用gridview中的链接按钮下载二进制文件(图像,pdf等)。
<asp:GridView Visible="true" ID="GridView1" runat="server" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
RowStyle-BackColor="#A1DCF2" AlternatingRowStyle-BackColor="White" AlternatingRowStyle-ForeColor="#000"
AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID"/>
<asp:BoundField DataField="FileName" HeaderText="File Name"/>
<asp:TemplateField HeaderText="Action" ItemStyle-HorizontalAlign = "Center">
<ItemTemplate>
<asp:LinkButton ID="lnkDownload" runat="server" Text="Download" OnClick="DownloadFile" CommandArgument='<%# Eval("Id") %>'></asp:LinkButton>
<asp:LinkButton ID="lnkDelete" runat="server" Text="Delete" OnClick="DeleteFile" CommandArgument='<%# Eval("Id") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
代码背后:
Protected Sub DownloadFile(sender As Object, e As EventArgs)
Dim id As Integer = Integer.Parse(TryCast(sender, LinkButton).CommandArgument)
Dim bytes As Byte()
Dim fileName As String, contentType As String
Using con As New SqlConnection(DataSource.ConnectionString)
Using cmd As New SqlCommand()
cmd.CommandText = "select FileName, PatImage, FileType from DB where Id=@Id"
cmd.Parameters.AddWithValue("@Id", id)
cmd.Connection = con
con.Open()
Using sdr As SqlDataReader = cmd.ExecuteReader()
sdr.Read()
bytes = DirectCast(sdr("PatImage"), Byte())
contentType = sdr("FileType").ToString()
fileName = sdr("FileName").ToString()
End Using
con.Close()
End Using
End Using
Response.Clear()
Response.Buffer = True
Response.Charset = ""
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.ContentType = contentType
Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName)
Response.BinaryWrite(bytes)
Response.Flush()
Response.End()
End Sub
但如果我的父aspx页面中有UpdatePanel
,则无效。所以我用Google搜索,我找到了答案;那就是在RowDataBound中放置代码:
Private Sub GridView1_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GridView1.RowDataBound
Dim lb As LinkButton = TryCast(e.Row.FindControl("lnkDownload"), LinkButton )
ScriptManager.GetCurrent(Me.Page).RegisterAsyncPostBackControl(lb)
End Sub
发生了新的错误。那就是我在我的GridView中使用我的RowDataBound中的代码找不到我的linkButton。
所以我再次搜索,我发现我应该在我的aspx页面ClientIDMode="AutoID"
中添加一个属性。但这仅适用于框架4.x.我不能这样做因为我目前正在使用3.5。在我目前的情况下是否有任何补救措施?
答案 0 :(得分:0)
已经找到答案,我刚刚更改了我的RowDataBound内容,请参阅代码:
Private Sub GridView1_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GridView1.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim LButton = CType(e.Row.FindControl("lnkDownload"), System.Web.UI.WebControls.LinkButton)
Dim scriptManager__1 = ToolkitScriptManager.GetCurrent(Me.Page)
If scriptManager__1 IsNot Nothing Then
scriptManager__1.RegisterPostBackControl(LButton)
End If
End If
End Sub