locked
How to add mutiple rows to DataTable using looping and then show it in a gridview RRS feed

  • Question

  • User-1382647668 posted
    con.Open();
    SqlCommand cmd = new SqlCommand("SELECT date,Project_Name FROM tbl_Project", con);
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    
    DataTable dt = new DataTable();
    DataTable dt1 = new DataTable();
    
    da.Fill(dt);
    if (dt1.Rows.Count > 0)
    {
    
    dt1.Columns.Add("Date", typeof(DateTime));
    dt1.Columns.Add("Project Name", typeof(string));
    
    GridView1.DataSource = dt1;
    DataRow dr = dt1.NewRow();
    
    for (int i = 0; i < dt1.Rows.Count; i++)
    {
    //change HeaderTemplate text, date to Date & Project_Name to Project Name in GridView1
    
    dr["Date"] = dt.Rows[i]["date"].ToString();
    dr["Project Name"] = dt.Rows[i]["Project_Name"].ToString();
    
    dt1.Rows.Add(dr);
    dr = dt1.NewRow();
    dt1.AcceptChanges();
    
    }
    
    //bind datatable in to gridview GridView1
    
    GridView1.DataSource = dt1;
    GridView1.DataBind();
    }
    con.Close();

    Saturday, January 4, 2014 5:19 AM

All replies

  • User1508394307 posted

    I think your code is non-sense without telling why user might need to have 2 data tables with same content.

    Why simply not to use only one?

    SqlCommand cmd = new SqlCommand("SELECT date,Project_Name FROM tbl_Project", con);
    
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    DataTable dt = new DataTable();
    da.Fill(dt);
    
    GridView1.DataSource = dt;
    GridView1.DataBind(); 

    or

    SqlCommand cmd = new SqlCommand("SELECT date,Project_Name FROM tbl_Project", con);
    cmd.Open();
     
    SqlDataReader reader = cmd.ExecuteReader();
           
    GridView1.DataSource = reader;
    GridView1.DataBind();

    Hope this helps.

    Saturday, January 4, 2014 5:36 AM
  • User-1382647668 posted

    Thanks for your reply,

         Also I want to change my HeaderTemplate text manually in the GridView. 

    Saturday, January 4, 2014 6:06 AM
  • User1508394307 posted

    I want to change my HeaderTemplate text

    What is the question here?

    Read documentation 

    http://msdn.microsoft.com/en-us/library/aa479342.aspx

    <asp:BoundField HeaderText="Name" 
    Saturday, January 4, 2014 6:16 AM