Search code examples
c#datatable

Cannot apply indexing to an expression type object


I have a very simple project in C# but i haven't don't much since i encounter errors as i progress. I do have a class called CUSTOMER and contains a few line of codes.

 public class Customer
{
    public int Id { get; set; }
    public string FirstName { get; set; }


    public Customer(DataRow row)
    {
        this.FirstName = row["FirstName"].ToString();
    }


    public List<Customer> GetCustomer()
    {
        List<Customer> c=new List<Customer>();
        DataTable dt=new DataTable();
        Dal.GetDataTable(dt, "select * from customer");
        foreach (var row in dt.Rows)
        {
            c.Add(new Customer(row["FirstName"]));  //Error here
        }
        return c;
    }
}

This code is pretty straightforward i believe, i want to retrieve a list of customers from a DataTable. According to the compiler:

Cannot apply indexing with [] to an expression of type 'object'

Thank you.


Solution

  • You error is here :

    foreach (var row in dt.Rows)
    {
         c.Add(new Customer(row["FirstName"]));
    }
    

    You should change it to match the constructor:

    foreach (DataRow row in dt.Rows)
    {
         c.Add(new Customer(row));
    }
    

    You constructor accepts a DataRow, so you need to pass a row and not an object( row["FirstName"]returns an object which is the FirstName value for the current row ).

    You also need to implicitly specify the type of the foreach variable (DataRow row in dt.Rows)