What is the best way to get a single value from a dataset?

I have a dataset in which there should be only one value, what is the best way to get this one value and an integer?

+4
source share
6 answers

SqlCommand.ExecuteScalar

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

See the new C # 3.0 “Extension Methods” feature. You can define your own extension method for any class. For instance:

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

After using it:

 using MyEx; public class Class1 { public void Test() { DataSet ds = new DataSet(); object value = ds.SingleValue(); } } 
+4
source
 if (ds.Tables[0].Rows.Count > 0) { int i = Convert.ToInt32(ds.Tables[0].Rows[0]["colname"]); } 
+1
source

the best way would be to not write a single value in the data set.

but if you cannot avoid this:

 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); } 
0
source

You can do it:

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

You can do it like this:

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

Source: https://habr.com/ru/post/1379973/


All Articles