简体   繁体   中英

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

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.

I am sure you can do something like this:

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM