首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >对不起作用的int值进行错误检查

对不起作用的int值进行错误检查
EN

Stack Overflow用户
提问于 2014-06-26 20:51:57
回答 1查看 112关注 0票数 0

我有一个函数,用于测试.csv中的字段是否包含有效的id (本例中为ProfileID)。我想检查非数字条目,如果是真的,则显示一条错误消息。但是,我不明白为什么我设置的函数无法捕获错误。导入过程仍然会生成一个错误页面,并显示消息:"Conversion when the nvarchar value '9b‘to data type int“(9B是我的测试.csv文件中的无效值)。

代码如下:

代码语言:javascript
复制
    bool RetVal = true;

    //PROFILEID
    string ProfileID = GetValue(row, (int)ProfileColumns.ProfileId);
    try
    {
        ProfileID = ProfileID.ToLower();
        int profIDCount = 0;

        int pnumber;
        bool presult = Int32.TryParse(ProfileID, out pnumber);

        if (presult == false)
        {
            ErrorLabel.Text += "Error Line " + LineCount + ": on " + ProfileID + " Invalid ProfileID<br />";
            RetVal = false;
        }

        else
        {
            string profIDSqlStr = string.Format("SELECT COUNT(*) AS 'ProfileID' FROM ProductProfile WHERE ProfileID=@ProfileID");
            using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["AbleCommerce"].ToString()))
            {
                SqlCommand cmd = new SqlCommand(profIDSqlStr, cn);
                cmd.Parameters.AddWithValue("@ProfileID", ProfileID);
                cn.Open();

                using (IDataReader reader = cmd.ExecuteReader())
                {
                    if (reader.Read())
                    {

                        profIDCount = Convert.ToInt32(reader["ProfileID"].ToString());
                    }
                    if (profIDCount <= 0)
                    {
                        ErrorLabel.Text += "Error Line " + LineCount + ": on " + ProfileID + " Invalid  Product Profile<br />";
                        RetVal = false;

                    }
                }
                cn.Close();
            }
        }
    }
    catch
    {
        ErrorLabel.Text += "Error Line " + LineCount + ": on " + ProfileID + " Error looking up product profile<br />";
        RetVal = false;
    }
EN

回答 1

Stack Overflow用户

发布于 2014-06-26 20:55:09

使用正确的类型,因此当它是int列时不是字符串。

替换

代码语言:javascript
复制
cmd.Parameters.AddWithValue("@ProfileID", ProfileID);

使用

代码语言:javascript
复制
cmd.Parameters.AddWithValue("@ProfileID", pnumber);  

已在Int32.TryParse中成功初始化pnumber

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24431053

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档