错误"输入字符串格式不正确"

时间:2014-09-04 19:40:48

标签: c# asp.net gridview

我正在使用asp.net,c#和SQL服务器开发一个Web应用程序项目。上传过程工作正常,但下载过程收到此错误“输入字符串格式不正确”。表中的列class_id是varchar,我在gridview

中将它用作DataKeyNames
<asp:LinkButton ID="lnkDownload" runat="server" Text="Download" OnClick="DownloadFile"
                CommandArgument='<%# Eval("class_id") %>'></asp:LinkButton>

以下代码用于在gridview中单击下载按钮时下载文件

 protected void DownloadFile(object sender, EventArgs e)
    {
        int class_id = int.Parse((sender as LinkButton).CommandArgument); // the error is here
        byte[] bytes;
        string fileName, contentType;
        string constr = ConfigurationManager.ConnectionStrings["connection"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand())
            {

                cmd.Connection = con;
                con.Open();
                using (SqlDataReader sdr = cmd.ExecuteReader())//Error is here
                {
                    sdr.Read();
                    bytes = (byte[])sdr["filePath"];
                    contentType = sdr["fileType"].ToString();
                    fileName = sdr["fileName"].ToString();
                }
                con.Close();
            }
        }
        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();
    }

如何解决此错误。 提前谢谢

1 个答案:

答案 0 :(得分:2)

来自命令的值类似于&#34; uc3f13se&#34;。然后你试图将它解析成一个整数。该值不是整数,因此int.Parse()将失败。

int class_id = int.Parse((sender as LinkButton).CommandArgument);

你可能只是将它用作字符串,CommandArgument很可能是一个字符串类型,已经给出了你给我的示例值:

var class_id = ((LinkButton)sender).CommandArgument;

当然,假设您的db中的class_id列是varchar或其他字符串接受类型。

如果您对int.Parse()有更多疑问,可以访问here,这会引发它抛出的异常以及如何导致它们。

相关问题