Search code examples
c#.netdatarow

how to add the rows to the datatable while executereader reads the rows from the table?


I want to add the rows that are read by executereader to the new datatable with C# coding


Solution

  • There are too many unknowns in your question. Foreg, is the data table typed or untyped? What are the column types? And so forth.

    But anyway, here's a general example. I adapted the code from the original sample given here.

    private static void ReadOrderData(string connectionString)
    {
        string queryString = "SELECT OrderID, CustomerID FROM dbo.Orders;";
    
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            SqlCommand command = new SqlCommand(queryString, connection);
            connection.Open();
    
            SqlDataReader reader = command.ExecuteReader();
    
            // Call Read before accessing data.
            while (reader.Read())
            {
               CustomersRow newCustomersRow = Customers.NewCustomersRow();
               newCustomersRow.CustomerID = reader[0].ToString();
               newCustomersRow.CompanyName = reader[1].ToString();
               dt.Rows.Add(newCustomersRow);
            }
    
            // Call Close when done reading.
            reader.Close();
        }
    }