Tuesday, February 23, 2010

How to convert SqlDataReader or DataReader to DataTable in Asp.Net




Please visit my new Web Site WWW.Codedisplay.com



In many cases we need to convert or converting SqlDataReader or DataReader to a DataTableto meet some technical challenges. Here i will show you converting SqlDataReader to a DataTable in a simple way. The code sample is given below:













protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string sql = "SELECT B.Name [Brand Name],C.Name [Category Name], " +
                    "P.Name [Product Name] FROM " +
                    "Brand B, Category C, Product P " +
                    "WHERE B.ID=P.BrandID AND C.ID=P.CategoryID Order BY 1,2,3";
            DataTable dt = new DataTable();
            using (SqlConnection oConn = new SqlConnection(ConfigurationManager.ConnectionStrings["TestConnection"].ConnectionString))
            {
                oConn.Open();
                SqlCommand cmd = new SqlCommand(sql, oConn);
                System.Data.SqlClient.SqlDataReader dr = cmd.ExecuteReader();
                dt.Load(dr);
            }

            Response.Write("Datatable row count: "+dt.Rows.Count.ToString());
        }
    }
Look at the code its self explanatory. So i hope that no need any explanation.

2 comments:

Anonymous said...

It's good example

Anonymous said...

Simple And Effective

Want to say something?
I WOULD BE DELIGHTED TO HEAR FROM YOU

Want To Search More?
Google Search on Internet
Subscribe RSS Subscribe RSS
Article Categories
  • Asp.net
  • Gridview
  • Javascript
  • AJAX
  • Sql server
  • XML
  • CSS
  • Free Web Site Templates
  • Free Desktop Wallpapers
  • TopOfBlogs
     
    Free ASP.NET articles,C#.NET,VB.NET tutorials and Examples,Ajax,SQL Server,Javascript,Jquery,XML,GridView Articles and code examples -- by Shawpnendu Bikash