10

I'm rewriting/converting some VB-Code:

Dim dt As New System.Data.DataTable()
Dim dr As System.Data.DataRow = dt.NewRow()
Dim item = dr.Item("myItem")

C#:

System.Data.DataTable dt = new System.Data.DataTable();
System.Data.DataRow dr = dt.NewRow();
var item = dr.Item["myItem"];

I can't make it run under C#, the problems I have is the third row var item = dr.Item["myItem"];:

System.Data.DataRow' does not contain a definition for 'Item' and no extension method 'Item' accepting a first argument of type 'System.Data.DataRow' could be found (are you missing a using directive or an assembly reference?)

I referenced System.Data Version 4 in both projects. What am I missing here? Note: ItemArray exists in both...

sl3dg3
  • 5,026
  • 12
  • 50
  • 74

2 Answers2

22

Try like this:

var item = dr["myItem"];

In C# you can access the indexer property directly. And the DataRow.Item property is defined as indexer.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Ah, this does the trick - I just wonder why there is a different behaviour/syntax/style compared to VB... – sl3dg3 Oct 24 '11 at 10:07
  • 2
    @sl3dg3 - if there weren't any differences in syntax/style/behaviour between C# and VB, they wouldn't be 2 different languages... – Damien_The_Unbeliever Oct 24 '11 at 10:11
  • @Damien_The_Unbeliever: Well, in VB you have the 'peace' of using both, means you also can write `dr("myItem")` - funny that C# denies the access to the item-property... – sl3dg3 Oct 24 '11 at 10:18
  • @sl3dg3, the "peace" of writing both forms, but the "pure evil" of having `()` as index-selector operators. ;) – hometoast Jan 31 '13 at 12:18
4

There is actually no "Item" property in C#. In VB the DataRow cell access is defined like this:

Default Public Property Item (
    column As DataColumn
) As Object

So there is a literal "Item" property. However, in C# it is defined like this:

public object this[
    DataColumn column
] { get; set; }

So this is the default property of the class / object. So you access it with the object name.

Pax
  • 41
  • 1