我正在尝试将 pdf 从我的数据库带到我的 gridview 并允许用户单击它并下载 pdf。我正在尝试解决这里解决的问题:
Accessing data from a BoundField of Gridview
但是,我收到以下错误:
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);
我仍然收到同样的错误。
最佳答案
您没有指定 CommandArgument
。因此,您的错误发生是因为您试图将空白字符串转换为整数。
添加行索引作为您的 CommandArgument
:
尝试将其添加到您的 Button
控件中:
<asp:Button ID="Button1"
ButtonType="Link"
CommandName="DownloadFile"
CommandArgument='<%#Container.DataItemIndex%>'
HeaderText="Download"
runat="server"
Text="Button" />
关于c# - gridview e.CommandArgument 字符串格式不正确,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11831394/