Wednesday, January 23, 2013

Convert Datareader to Datatable in asp.net



using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page
{
    IDataAdapter da;
    DataSet ds = new DataSet();
    protected void Page_Load(object sender, EventArgs e)
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("ID", typeof(string));
        dt.Columns.Add("Name", typeof(string));
        dt.Columns.Add("Age", typeof(string));
        dt.Columns.Add("Address", typeof(string));
        DataRow drQuery;
      
      
        da = getReader();

        da.Fill(ds);
        int QCount1 = 0;
        while (QCount1 < ds.Tables[0].Rows.Count)
        {
            drQuery = dt.NewRow();

            drQuery["ID"] = Convert.ToString(ds.Tables[0].Rows[QCount1][1].ToString());
            drQuery["Name"] = ds.Tables[0].Rows[QCount1][3].ToString();
            drQuery["Age"] = ds.Tables[0].Rows[QCount1][2].ToString();
            drQuery["Address"] = ds.Tables[0].Rows[QCount1][9].ToString();
            dt.Rows.Add(drQuery);
            QCount1 = QCount1 + 1;
        }
      
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }

    private IDataAdapter getReader()
    {
     
    
        SqlConnection con = newSqlConnection(ConfigurationManager.ConnectionStrings["testcon"].ToString());
        SqlDataAdapter da = new SqlDataAdapter("select * from t_users",con);
      


        return da;
    }
}



No comments:

Post a Comment