gridview e.CommandArgument字符串格式不正确

时间:2012-08-06 15:35:08

标签: c# asp.net gridview

我正在尝试将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);

我仍然收到同样的错误。

2 个答案:

答案 0 :(得分:4)

您没有指定CommandArgument。因此,您的错误正在发生,因为您正在尝试将空字符串转换为整数。

将行索引添加为CommandArgument

尝试将此添加到Button控件中:

<asp:Button ID="Button1"
            ButtonType="Link"
            CommandName="DownloadFile"
            CommandArgument='<%#Container.DataItemIndex%>'
            HeaderText="Download"
            runat="server"
            Text="Button" />

答案 1 :(得分:3)

您没有为CommandArgument分配值,而是在导致错误的RowCommand中访问它们。

 <asp:Button ID="Button1" ButtonType="Link" CommandName="DownloadFile" HeaderText="Download"  runat="server" Text="Button" CommandArgument="1" />

您可以使用绑定值替换硬编码的CommandArgument值,如@Curt告诉的那样。

CommandArgument='<%#eval("DataField")'

使用ToString

int index = Convert.ToInt32(e.CommandArgument.ToString());