ds.Tables[0] causes error

BenTam-3003 686 Reputation points
2022-01-24T14:18:47.12+00:00

Dear All

string connstr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=School.accdb";
     OleDbConnection connection = new OleDbConnection(connstr );
     connection.Open();
     string sql = "select * from Student";
     OleDbDataAdapter adapter = new OleDbDataAdapter(sql, connection);
     DataSet set=new DataSet();  
     adapter.Fill(set);
     var table=set.Tables[0];
     var result = table.AsEnumerable().Select(x => x.Field<int>("Age")).Take(1);
     Console.WriteLine("First student Age is "+result.First());

In the above code, the line "ds.Tables[0]" causes error. Could anybody help me?

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,199 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Ken Tucker 5,846 Reputation points
    2022-01-24T17:24:21.067+00:00

    The error is because query is not returning any results. I would check that the database is making it to the bin folder of your app when debugging. I would also verify the table name.


  2. AgaveJoe 26,186 Reputation points
    2022-01-25T13:36:06.61+00:00

    Your latest code returns a single column "ID" but the LINQ query is looking for "Age".