Wednesday, March 7, 2012

How to count the records in a datatable

I have the following:

Dim ResourceAdapter As New ResourcesTableAdapters.ResourcesTableAdapter
Dim dF As Data.DataTable = ResourceAdapter.GetDataByDistinct
Dim numRows = dF.Rows.Count
Dim dS As Data.DataTable = ResourceAdapter.CountQuery
Dim sumRows = dS.Rows.Count
DataList1.DataSource = dF
DataList1.DataBind()
LblCount.Text = numRows
LblSum.Text = sumRows

numRows is the number of records in a particular category. CountQuery is a method that returns the total number of records in all the categories. I don't know how to get the result of that query, the code line in bold isn't right. How do I get this number?

Diane

ds.Rows[0][0].ToString()

If you are getting a single count value, you can use the above statement. Make sure you validate nulls, else an exception will be raised

Thanks

|||

Thank you.

Dim ResourceAdapter As New ResourcesTableAdapters.ResourcesTableAdapter
Dim dF As Data.DataTable = ResourceAdapter.GetDataByDistinct
Dim numRows = dF.Rows.Count
Dim dS As Data.DataTable = ResourceAdapter.CountQuery
Dim sumRows = ds.Rows[0][0].ToString()

But before I can assign the count to sumRows, don't I have to fix the line above it (in bold)? That line gives me the compiler error

Value of type 'System.Nullable(Of Integer)' cannot be converted to 'System.Data.DataTable'.

Diane

|||

Are you sure ResourceAdapter.CountQuery returns a datatable? If so check if you have any rows available or not first

If (ds.Rows.Count > 0)
Dim sumRows = ds.Rows(0)(0).ToString() /// i am c# code, not sure of how you refer a two dimensional arrary
End If

Thanks

|||

I'm not sure what it returns. The query is one that's designed to return only one row, the number of records in the table. I'm not sure how to get that.

Diane

|||

Looking at the error you are getting (ie: Value of type 'System.Nullable(Of Integer)' cannot be converted to 'System.Data.DataTable'. )

I would say you need to have

Dim sumRows as Int

sumRows = ResourceAdapter.CountQuery

No comments:

Post a Comment