我正在尝试将 pdf 从我的数据库中带到我的 gridview 并允许用户单击它并下载 pdf。我正在尝试关注此处已解决的问题:
但是,我收到以下错误:
Input string was not in a correct format.
这是我的 asp.net 代码:
<Columns>
<asp:CommandField ShowEditButton="True" ControlStyle-CssClass="savefile"/>
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False"
ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="event_name" HeaderText="event_name"
SortExpression="event_name" />
<asp:TemplateField HeaderText="PDF">
<ItemTemplate>
<asp:Button ID="Button1" ButtonType="Link" CommandName="DownloadFile" HeaderText="Download" runat="server" Text="Button" />
</ItemTemplate>
<EditItemTemplate>
<asp:FileUpload ID="FileUpload1" runat="server" /> // shown only in edit mode
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
和相应的c#代码:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "DownloadFile")
{
int index = Convert.ToInt32(e.CommandArgument);
string id = GridView1.DataKeys[index].Value.ToString();
SqlConnection con = new SqlConnection(strcon);
string command = "Select pdf from table where id = @id";
SqlCommand cmd = new SqlCommand(command, con);
cmd.Parameters.AddWithValue(id, "id");
SqlDataReader reader = cmd.ExecuteReader();
reader.Read();
Response.Clear();
Response.ContentType = "application/pdf";
Response.BinaryWrite((Byte[])reader[0]);
Response.Flush();
Response.End();
}
}
我的 c# 代码中的错误行是这样的:
int index = Convert.ToInt32(e.CommandArgument);
提前感谢您的帮助!
编辑 - - - - - - - - - - - - - - - - - - - - - - - - - -
我的按钮字段现在看起来像这样:
<asp:Button ID="Button1" ButtonType="Link" CommandName="DownloadFile" CommandArgument='<%#Container.DataItemIndex%>' HeaderText="Download" runat="server" Text="Button" />
和我的 c# 错误代码行:
int index = Convert.ToInt32(e.CommandArgument);
我仍然收到同样的错误。