tags:

views:

32

answers:

2
conn = new SqlConnection(@"Data Source=ASHISH-PC\SQLEXPRESS; initial catalog=bank; integrated security=true");
ada = new SqlDataAdapter("select total_amount from debit_account where account_no=12", conn);
ds = new DataSet();

ada.Fill(ds);

Now, I want to print value of the dataset... how? Please help me.

+2  A: 

I think, in this case, you'd be better off (performance-wise) to use a SqlCommand instead of the adapter and dataset, and invoke the ExecuteScalar method.

See http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar.aspx

If you must use the data set, however, ds.Tables[0].Rows[0]["total_amount"] should retrieve your value. You will probably need to type cast the value, though.

kbrimington
+4  A: 

I'd suggest that the best option here isn't actually a SqlDataAdapter and DataSet, but rather a SqlCommand. Try this:

using(SqlConnection conn = new SqlConnection(@"Data Source=ASHISH-PC\SQLEXPRESS; initial catalog=bank; integrated security=true"))
{
    conn.Open()
    using (SqlCommand command  = new SqlCommand("select total_amount from debit_account where account_no=12", conn)
    {
        var result = command.ExecuteScalar();
        Console.WriteLine("The total_amount for the account is {0}", result);
    }
}

The ExecuteScalar() method on SqlCommand returns the value in the first column of the first row that your query returns, which is ideal in this situation.

If you absolutely have to use a dataset then you'd want to do the following:

using(SqlConnection conn = new SqlConnection(@"Data Source=ASHISH-PC\SQLEXPRESS; initial catalog=bank; integrated security=true"))
{
    conn.Open()
    using (SqlDataAdapter adapter = new SqlDataAdapter("select total_amount from debit_account where account_no=12", conn)
    {
        var ds = new DataSet();
        adapter.Fill(ds);
        Console.WriteLine("The total_amount for the account is {0}", ds.Tables[0].Rows[0][0]); // Get the value from the first column of the first row of the first table
    }
}

Note: I've wrapped both examples in the C# using statement, this ensures that all your database resources are cleaned up so you don't have any problems with with leaking unmanaged resources. It's not particularly difficult or complicated so is well worth doing

Rob
+1. This example is complete and properly handles `IDisposable` classes.
kbrimington
@Rob-- thank you rob ......it is working fine
ashish
@ashish, if it answers your question, please click on the hollow tick to the left of this answer to mark it as your "accepted answer" =)
Rob