• How to convert DataReader to DataTable

    Posted on February 15, 2013 by in Dotnet Tips & Tricks, Tips & Tricks

    public static void LoadDataReaderIntoDataTable()
        IDataReader dr;
        DataTable dtProducts = new DataTable();;
        //fetch the connection string from app.config
        string connString = ConfigurationSettings.AppSettings["Sql"];
        //Open SQL Connection
        using (SqlConnection conn = new SqlConnection(connString))
            //Initialize command object
            using (SqlCommand cmd = new SqlCommand("SELECT TOP 10 Name, ProductNumber, ListPrice FROM Production.Product", conn))
                //set the command type  to stored procedure
                cmd.CommandType = CommandType.Text;
                //execute the stored procedure
                dr = cmd.ExecuteReader();
                //Fill the ataTable with values from IDataReader
        Console.WriteLine("/*********Product Properties ***************/");
        foreach (DataRow drow in dtProducts.Rows)
            //print Product properties                
            Console.WriteLine("{0}\t{1}", "Product Name:", drow["Name"]);
            Console.WriteLine("{0}\t{1}", "Product Number:", drow["ProductNumber"]);
            Console.WriteLine("{0}\t{1}", "List Price:", drow["ListPrice"]);

    convert datareader to datatable

    Be Sociable, Share!
      Post Tagged with , , ,

    Written by

    View all articles by

    Email : [email protected]

    Leave a Reply