title: Create GridView rows using GridViewRow object in Code Behind Using C#
body: <p>I want to create a GridView Control in Code Behind.</p>
  
  <p>Data is fetched from database table.</p>
  
  <p>My code is:</p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Web;
  using System.Web.UI;
  using System.Web.UI.WebControls;
  using System.Data;
  using System.Data.SqlClient;
  
  public partial class gv1 : System.Web.UI.Page
  {
      SqlConnection cn;
     SqlCommand cmd;
     DataSet ds;
     SqlDataAdapter da;
  
     protected void Page_Load(object sender, EventArgs e)
    {
         cn = new SqlConnection("Data Source=AMIR-PC\\MOHEMMAD;Initial Catalog=CRM_InvestPlus;Integrated Security=True");
  
  }
  protected void Button1_Click(object sender, EventArgs e)
  {
      cn.Open();
      cmd = new SqlCommand("Select * from Customer_Master", cn);
      da = new SqlDataAdapter(cmd);
      ds = new DataSet();
      da.Fill(ds);
      cn.Close();
  
      GridView gr1 = new GridView();
  
      for (int i = 0; i &lt; ds.Tables[0].Rows.Count; i++)
      {
          GridViewRow row = new GridViewRow(i, i, DataControlRowType.DataRow,  DataControlRowState.Normal);
          TableCell cell1 = new TableCell();
          TableCell cell2 = new TableCell();
          cell1.Text = ds.Tables[0].Rows[i][0].ToString();
          cell2.Text = ds.Tables[0].Rows[i][0].ToString();
          row.Cells.Add(cell1);
          row.Cells.Add(cell2);
          gr1.Controls[0].Controls.AddAt(i, row);
  
  
        }
          this.Controls.Add(gr1);
     }
  }
  </code></pre>
  
  <p>But when I Run the code error occurs as follows:</p>
  
  <p>ArgumentOutOfRangeException was unhandled by user at the line of code showing  </p>
  
  <p>gr1.Controls[0].Controls.AddAt(i,row);  </p>
  
  <p>Please help..<br>
  Thanks in advance..  </p>