Steve
Steve

Reputation: 123

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

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?

Upvotes: 4

Views: 4895

Answers (6)

rahularyansharma
rahularyansharma

Reputation: 10777

if (ds.Tables[0].Rows.Count > 0) {
    int i = Convert.ToInt32(ds.Tables[0].Rows[0]["colname"]);
}

Upvotes: 1

rockyashkumar
rockyashkumar

Reputation: 1332

You can do it like this...

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

Upvotes: 0

Don Tomato
Don Tomato

Reputation: 3539

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();
    }
}

Upvotes: 4

fixagon
fixagon

Reputation: 5566

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

but if you cant avoid it:

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

Upvotes: 0

KMC
KMC

Reputation: 20046

you can do this:

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

Upvotes: 0

John Buchanan
John Buchanan

Reputation: 5242

SqlCommand.ExecuteScalar

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

Upvotes: 6

Related Questions