2011-11-07 88 views

回答

6

SqlCommand.ExecuteScalar

// setup sql command and sql connection etc first... 
int count = (int) cmd.ExecuteScalar(); 
+1

這比使用一個數據集就是我想要做的更好,好:) – Steve

+0

+1,好趕上! – sll

+0

+1:Linq to SQL是另一個類似的選擇。 –

0

最好的辦法是不要寫在數據集中的單個值。

,但如果你不能避免它:

try 
{ 
    //if the value is coming back as string 
    int value1 = Int32.Parse(ds.Tables[0].Rows[0][0].ToString()); 
    //if the value is already an integer 
    int value2 = (int)ds.Tables[0].Rows[0][0]; 
} 
catch(Exception ex) 
{ 
    throw new Exception("You do not have even a single value in the DataSet or its not an integer!", ex); 
} 
1
if (ds.Tables[0].Rows.Count > 0) { 
    int i = Convert.ToInt32(ds.Tables[0].Rows[0]["colname"]); 
} 
+0

雖然這段代碼可能會回答這個問題,但提供關於爲什麼和/或代碼如何回答這個問題的附加上下文會提高它的長期價值。 –

0

,你可以這樣做:

dt = ds.Tables["TableName"]; 
Convert.ToInt32(dt.Rows[rowNumber]["ColumnName"].ToString()); 
0

你可以做這樣的...

int myVar = 
Convert.ToInt32(dsMyDataSet.Tables["MyTable"].Rows[intRowPos]["MyColumn"].Tostring()); 
+0

沒有從對象轉換爲decimal或int –

4

見C#3.0'擴展方法'的新特性您可以爲任何類定義您自己的擴展方法。 例如:

namespace MyEx; 

public static class MyExtensions 
{ 
    public static object SingleValue(this DataSet ds) 
    { 
     return ds.Tables[0].Rows[0][0]; 
    } 
} 

後,您可以使用它:

using MyEx; 

public class Class1 
{ 
    public void Test() 
    { 
     DataSet ds = new DataSet(); 
     object value = ds.SingleValue(); 
    } 
} 
相關問題