Confused about the DataRow object

  • Thread starter Thread starter Duane Roelands
  • Start date Start date
D

Duane Roelands

I'm having a frustrating problem with some simple code. Isn't that
always the case? :)

Here's the code in question...

Public Sub GetAllEmployees()

Dim tbl As DataTable = EmpDataSet.Tables(0)
Dim Row As DataRow
Dim MyString As String

For Each Row In tbl.Rows
Debug.WriteLine(Row(0)) '' This line builds fine
MyString = Row(0) '' This line does not build
Next

End Sub

The IDE won't build this code, and mousing over the little squigglies
gives me "Option Strict On disallows implicit conversions from
'System.Object' to 'String'".

If I comment out the "MyString" line, the code builds and runs as you
would expect. This code follows just about every example I've seen of
looping through the rows in a datatable.

Now, I know that I can change the "MyString" line to this...

MyString = CStr(Row(0))

....and it will build and run fine, but I'm not sure why I should have
to do that, or why none of the examples that I'm seeing require such
an explicit conversion.

Thanks in advance.

Duane
 
Hi Duane,

Item property of Row returns an Object and not a String.
If you have option strict on then (as you discovered) you have to either
cast it or convert it.
 
'm having a frustrating problem with some simple code. Isn't that
always the case? :)

Here's the code in question...

Public Sub GetAllEmployees()

Dim tbl As DataTable = EmpDataSet.Tables(0)
Dim Row As DataRow
Dim MyString As String

For Each Row In tbl.Rows
Debug.WriteLine(Row(0)) '' This line builds fine
MyString = Row(0) '' This line does not build
Next

End Sub

The IDE won't build this code, and mousing over the little squigglies
gives me "Option Strict On disallows implicit conversions from
'System.Object' to 'String'".

The WriteLine method is probably automatically calling the "ToString()"
method on the object passed in -- in this case, the value of the first
column.

You need to do the same thing to convert the "object" returned by
accessing Row(0) to a string:

MyString = Row(0).ToString()
 
Patrick Steele said:
The WriteLine method is probably automatically calling the "ToString()"
method on the object passed in -- in this case, the value of the first
column.

You need to do the same thing to convert the "object" returned by
accessing Row(0) to a string:

MyString = Row(0).ToString()

Thanks for the replies. I did end up casting the Row object with
CStr(), so my code is building and running. I'm a little disappointed
that so many examples of how to do this (from both Microsoft and other
sources) appear to be just plain wrong. Perhaps it was different in
Beta.

No matter. I'm grateful for the answers and I really enjoy .NET
coding. :) Thanks again, and Happy New Year!
 
Back
Top