Reputation: 5459
I just learnead to use a strongly typed dataset along with stored procedures today and things are going very well , except one little problem.I can figure out how to get my data out of a datatable with itarating over it considering the fact that the datable has only one column with one row in it.This is what I have so far:
var bookCountAdapter = new CountBooksTableAdapter();
var bookCountDataTable = new BooksAndCategoriesDataSet.CountBooksDataTable();
bookCountAdapter.Fill(bookCountDataTable);
int totalNumberOfBooks = 0;
foreach (BooksAndCategoriesDataSet.CountBooksRow row in bookCountDataTable) {
totalNumberOfBooks = row.TotalNumberOfBooks;
}
return totalNumberOfBooks;
THe store procedure that is used by the dataset is:
CREATE PROCEDURE [dbo].[CountBooks]
AS
SELECT COUNT(*) FROM Books
Now my curent code works just fine.The problem is that I do not see a reason for itarating over bookCountDataTable
because I have in it only one element of type int and I only want to retrieve that.
Is there a way I could get that element by writing something similar like this :
bookCountDataTable.TotalNumberOfBooks
Upvotes: 1
Views: 856
Reputation: 68440
If you're sure you will have a single element you could do something like this
int totalNumberOfBooks = bookCountDataTable[0].TotalNumberOfBooks;
In any case you shouldn't be using a data set for retrieving a single value. There're better ways to do this as SqlCommand.ExecuteScalar
Even on your typed data set you could use the wizard on design view to create a query that returns a single value.
Upvotes: 1
Reputation: 1219
I am sure you can do something like this:
if(bookCountDataTable.Rows.Count > 0)
{
totalNumberOfBooks = Convert.ToInt32(bookCountDataTable.Rows[0]["TotalNumberOfBooks"]);
}
Upvotes: 2
Reputation: 223412
because I have in it only one element of type int and I only want to retrieve that.
Access it with the index then like:
return bookCountDataTable[0].TotalNumberOfBooks
But you should check the Row count for the table before.
From your foreach loop it looks like if there are going to be multiple rows in there then the last one's TotalNumberofBooks
will be returned.
Upvotes: 2