[英]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: 我今天刚学会使用强类型数据集和存储过程,除一个小问题外,一切进行得很顺利。考虑到datable具有以下事实,我可以找出如何从数据表中获取数据并对其进行实例化:只有一列其中一行。这是我到目前为止的内容:
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. 现在我的当前代码可以正常工作了,问题在于我看不到对bookCountDataTable进行
bookCountDataTable
的原因,因为我只有一个int类型的元素,而我只想检索它。
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.
因为我只有一个int类型的元素,所以我只想检索它。
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. 从您的foreach循环中看起来,如果其中将有多行,则将返回最后一行的
TotalNumberofBooks
。
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
有更好的方法来执行此操作,如
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. 即使在键入的数据集上,也可以使用设计视图上的向导来创建返回单个值的查询。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.