2011-11-20 76 views
0

Im選擇查詢中有多少行的計數。我需要將它分配給一個int變量。我怎麼做到這一點?查詢返回行數並分配給Int變量

Display.aspx.cs

  **int TotalYesVotes;** 
      Ratings GetYesVotes = new Ratings(); 
      DataTable DATotalYesVotes = GetYesVotes.GetTotalYesVotes(); 
      **//How do i assign that count to TotalYesVotes** 

業務層

 public DataTable GetTotalYesVotes() 
    { 

     DLRatings DlTotalyesVotes = new DLRatings(); 
     return DlTotalyesVotes.GetTotalYesVotes(); 

    } 

我的數據層

public DataTable GetTotalNoVotes() 
    { 
     //get database connection string from config file 
     string strConectionString o= ConfigurationManager.AppSettings["DataBaseConnection"]; 

     //set up sql 
     string StrSql = "SELECT COUNT(*) AS Expr1 FROM Ratings WHERE (PicRating = 2) AND (PicID = 2)"; 

     DataTable dt = new DataTable(); 
     using (SqlDataAdapter daObj = new SqlDataAdapter(StrSql, strConectionString)) 
     { 

      //fill data table 
      daObj.Fill(dt); 
     } 
     return dt; 
     } 
+1

如果'GetTotalNoVotes'的目的是檢索標量值,爲什麼要返回一個數據表? –

回答

2

你應該改變周圍有很多數據檢索:

public int GetTotalNoVotes() 
    { 
     //get database connection string from config file 
     string strConectionString o= ConfigurationManager.AppSettings["DataBaseConnection"]; 

     SqlConnection conn = new SqlConnection(strConnectionString); 
     conn.Open(); 

     SqlCommand oCommand = new SqlCommand("SELECT COUNT(1) AS Expr1 FROM Ratings WHERE (PicRating = 2) AND (PicID = 2)", conn); 

     object oValue = oCommand.ExecuteScalar(); 

     conn.Close(); 

     if (oValue == DBNull.Value) { 
      return 0; 
     } else { 
      return Convert.ToInt32(oValue); 
     } 
    } 
相關問題