Search code examples
c#sql-serverdataadapter

DataAdapter.Fill returns the row count but Rows.List is null


I'm really puzzled about this. I have a table in SQL Server with three nvarchar(255) columns and a couple rows just for testing. the following code correctly returns the column names and the row count of 2 but Rows.List = null. If I use reader.Read() I can read the data in the rows so the query is returning the data. Any query that alters the data in the tables such as an INSERT INTO ... will work perfectly.

    DataTable results = new DataTable;
    int rowsAffected = 0;
    string connectionString = "Server=<serverName>;Database=<databaseName>;Integrated Security=SSPI";
    string query = "SELECT * FROM testTable";
    using (SqlConnection conn = new SqlConnection(connectionString))
    using (SqlCommand command = new SqlCommand(query, conn))
    using (SqlDataAdapter dataAdapter = new SqlDataAdapter(command))
         rowsAffected = dataAdapter.Fill(results);

When this is done, results.Rows.Count = 2 which is correct, and results.Rows.List = null which is WRONG. Why isn't there any data being returned to me?


Solution

  • I'm not sure what you are trying to accomplish, but the method DataRowCollection.List is 1.) protected, so you probably just see it's value in the debugger, and 2.) returns always null because this is the reflected implementation:

    protected virtual ArrayList List => (ArrayList) null;
    

    You have already the DataRowCollection in results.Rows, so you can either enumerate it in a foreach or access s DataRow via it's index. If you really want a List<DataRow> you could use:

    List<DataRow> rowList = results.AsEnumerable().ToList();
    

    If you want a DataRow[] use ToArray instead.