Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

asp.net

I have a dataset that should have only one value in it, what is the best way to get that single value out and into an integer?

like image 568
Steve Avatar asked Dec 22 '22 06:12

Steve


2 Answers

SqlCommand.ExecuteScalar

// setup sql command and sql connection etc first...
int count = (int) cmd.ExecuteScalar();
like image 188
John Buchanan Avatar answered Jan 25 '23 22:01

John Buchanan


See a new feature of C# 3.0 'Extension Methods' You can define your own extension method for any class. For example:

namespace MyEx;

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

After you can use it:

using MyEx;

public class Class1
{
    public void Test()
    {
        DataSet ds = new DataSet();
        object value = ds.SingleValue();
    }
}
like image 39
Don Tomato Avatar answered Jan 25 '23 22:01

Don Tomato