2011-12-21 82 views
0

下面是我用於從列nos中獲取計數的那段代碼。在SQL Server中使用count()

//get max count of orders on server .2 
    public int getmaxcountfornos(string caseno,TextBox TextBox3) 
    { 
     int count2 = 0; 
     try 
     { 
      String dd_webCofig = ConfigurationManager.ConnectionStrings["counton140"].ConnectionString; 
      OdbcConnection ddlistconn = new OdbcConnection(dd_webCofig); 
      ddlistconn.Open(); 

      string cnt_2 = "select count(nos) from training_jud.orders where [email protected] and [email protected]"; 
      OdbcCommand ddlistCmd_2 = new OdbcCommand(cnt_2, ddlistconn); 

      ddlistCmd_2.Parameters.AddWithValue("b", caseno); 
      ddlistCmd_2.Parameters.AddWithValue("c", Convert.ToDateTime(TextBox3.Text).ToString("yyyy-MM-dd")); 

      count2 = (int)ddlistCmd_2.ExecuteScalar(); 
     } 

     catch (Exception ee) 
     { 
      HttpContext.Current.Response.Write(ee.Message); 
     } 
     return count2; 
    } 

在這裏,我得到異常作爲

指定的轉換是無效的。

任何人都可以幫我理清這個問題嗎?

回答

1

試試這個:

//get max count of orders on server .2 
public int getmaxcountfornos(string caseno,TextBox TextBox3) 
{ 
    int count2 = 0; 
    try 
    { 
     String dd_webCofig = ConfigurationManager.ConnectionStrings["counton140"].ConnectionString; 
     OdbcConnection ddlistconn = new OdbcConnection(dd_webCofig); 
     ddlistconn.Open(); 

     string cnt_2 = "select count(nos) from training_jud.orders where [email protected] and [email protected]"; 
     OdbcCommand ddlistCmd_2 = new OdbcCommand(cnt_2, ddlistconn); 

     ddlistCmd_2.Parameters.AddWithValue("**@b**", caseno); 
     ddlistCmd_2.Parameters.AddWithValue("**@c**", Convert.ToDateTime(TextBox3.Text).ToString("yyyy-MM-dd")); 

     count2 = **Convert.ToInt32**(ddlistCmd_2.ExecuteScalar()); 
    } 

    catch (Exception ee) 
    { 
     HttpContext.Current.Response.Write(ee.Message); 
    } 
    return count2; 
} 
0
count2 = int.Parse(ddlistCmd_2.ExecuteScalar().ToString()); 

使用代替

count2 = (int)ddlistCmd_2.ExecuteScalar(); 

上述問題解決了。

+1

可能是因爲ExecuteScalar'的'結果不是INT。這可能是一個長期的,或一個單位。在這種情況下演員陣容不會奏效。通過一個字符串(不要這樣做)解決這個問題。找出執行查詢後實際返回的類型。 – 2011-12-21 07:47:25

0

到目前爲止,您的代碼會好,但是請你用下面的代碼部分嘗試,感謝

string cnt_2 = "select count(nos) as OrderCount from training_jud.orders where [email protected] and [email protected]"; 
OdbcCommand ddlistCmd_2 = new OdbcCommand(cnt_2, ddlistconn); 

ddlistCmd_2.Parameters.AddWithValue("@b", caseno); 
ddlistCmd_2.Parameters.AddWithValue("@c", Convert.ToDateTime(TextBox3.Text).ToString("yyyy-MM-dd")); 

count2 = Convert.ToInt32(ddlistCmd_2.ExecuteScalar());