无法将参数值从String转换为Int32。 C#

时间:2017-03-16 13:34:42

标签: c# asp.net

请帮助您使用下面的C#代码。当我使用数值时,代码工作找到,但当我使用像K083271这样的值测试代码时,我有错误:

  

类型' System.FormatException'的例外情况发生在   System.Data.dll但未在用户codeAdditional中处理   信息:无法将参数值从String转换为   INT32。

调试提供usercount = 0

C#代码

using (SqlConnection con = new    SqlConnection(WebConfigurationManager.ConnectionStrings["Molecular"].ConnectionString))
    {
       con.Open();

 using (SqlCommand cmd = new SqlCommand(@"SELECT  count(*)

         from Patient  where MBID = @SearchCriteria ", con))
      {
           cmd.Parameters.Add("@SearchCriteria", SqlDbType.Int).Value= Convert.ToString(txtSearchCriteria.Text);

             DataTable dt = new DataTable();
             SqlDataAdapter da = new SqlDataAdapter(cmd);
             int userCount = (Int32)cmd.ExecuteScalar();
             da.Fill(dt);

          if (userCount > 0)
             {

                 using (SqlCommand cmd4 = new SqlCommand(@"SELECT  *

                        from Patient  where MBID = @SearchCriteria ", con))
                   {
                         int searchcriteria4 = int.Parse(txtSearchCriteria.Text);
                          cmd4.Parameters.AddWithValue("@SearchCriteria", searchcriteria4);
                          DataTable dt4 = new DataTable();
                          SqlDataAdapter da4 = new SqlDataAdapter(cmd4);

                           da4.Fill(dt4);

                                if (da4 != null)
                                {
                                    GridViewClinicalPatientDetails.DataSource = dt4;
                                    GridViewClinicalPatientDetails.DataBind();
                                }
                         }
                            return true;
                        }
           else
              {
                            Response.Write("<script>alert('Patient does not exist. Check Patient MBID')</script>");

                            txtSearchCriteria.Text = "";
                            return false;
              }
        }

2 个答案:

答案 0 :(得分:1)

在尝试执行查询之前检查用户输入:如果用户输入了不是整数的内容,请用#34之类的东西警告他;请插入一个数字&#34;并继续。 你可以使用这样的东西:

public class ApiFactory {

/**
 * Base URL for API calls
 */
private static final String BASE_URL = "";

public ApiFactory() {
}

private static Retrofit provideRestAdapter() {

    return new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .client(BaseApplication.getInstance().getOkHttpClient())
            .addConverterFactory(GsonConverterFactory.create())
            .addConverterFactory(ScalarsConverterFactory.create())
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .build();
}

public static <S> S createService(Class<S> serviceClass) {
    return provideRestAdapter().create(serviceClass);
}

答案 1 :(得分:-1)

使用belo command.Parameters.Add(&#34; @ SearchCriteria&#34;,0);