Search code examples
c#ado.netdatasetstrongly-typed-dataset

Getting one element from a strongly typed data set


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

Solution

  • I am sure you can do something like this:

    if(bookCountDataTable.Rows.Count > 0)
    {
         totalNumberOfBooks = Convert.ToInt32(bookCountDataTable.Rows[0]["TotalNumberOfBooks"]);
    }