tags:

views:

254

answers:

5

The following code does not compile

<ul>
<%
foreach( var row in SomeDataTable.Rows)
{
%>
  <li>
   <%= Html.ActionLink( row["field1"].ToString(), "action", new { } ) %>
  </li>
<%
}v
%>
</ul>

the error is - cannot apply indexing with [] to an expression of type 'object'

var is supposed to be implicit type ?

What gives ?

NOTE - I know it is bad practice to use DataTable/Dataset as is etc etc so hold your horses on that one if you can please :)

+3  A: 

Shouldn't it be row["field1"] and not item["field1"]?

mgroves
thanks for pointing it out, it's fixed
No problem, just click that little checkmark there :)
mgroves
A: 

You need to use

row["field1"]

instead of

item["field1"]
Serhat Özgel
done...........
A: 

Does it have something to do w/ you calling item["field1"] but you named the iterator variable "row"?

James Alexander
no, in that case the error would be - the name 'item' does not exist in the current contextit's fixed however
A: 

What happens when you cast it as a DataRow?

(DataRow row in SomeDataTable.Rows)
mxmissile
that works of course !
+2  A: 

DataRowCollection does not implement IEnumberable<DataRow> only IEnumerable. You will need to first call SomeDataTable.Rows.Cast<DataRow>() in your foreach or not use var, as mxmissle suggests.

IEnumerable<DataRow> is required for the compiler to know what type is enumerated over, which is required for this use of var.

Kleinux
Kumar, yes it is syntactic sugar. The problem here is that IEnumerable does not give the compiler enough info to determine what is coming out of Table.Rows. In this case the var keyword is the same as foreach (object row in table.Rows)It is for this reason that modern generic collections or lists all implement the IEnumerable<T> interface. I do not know why the DataRowCollection wasn't updated to support this. It can be a little annoying
Kleinux
yet somehow the compiler works withforeach( DataRow row in Table.Rows ) // compiles fineOr is it possible that the use of var requires IEnumberable<T> as inforeach(var row in Table.Rows ) // doesn't compilewhich is really the question here