Divya Diya

Divya Diya

  • NA
  • 116
  • 479

Index was out of range

Jan 29 2018 9:46 PM
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
 

This is my code:
private SqlConnection conn = new SqlConnection(@"Data Source=ADMIN-PC\SQLEXPRESS;Initial Catalog=task;User ID=sa;Password=ups");
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) {
gvbind();
}
}
protected void gvbind() {
conn.Open();
SqlCommand cmd = new SqlCommand("Select * from Customers", conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
conn.Close();
if (ds.Tables[0].Rows.Count > 0) {
GridView1.DataSource = ds;
GridView1.DataBind();
} else {
ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
GridView1.DataSource = ds;
GridView1.DataBind();
int columncount = GridView1.Rows[0].Cells.Count;//error occured in this line
GridView1.Rows[0].Cells.Clear();
GridView1.Rows[0].Cells.Add(new TableCell());
GridView1.Rows[0].Cells[0].ColumnSpan = columncount;
GridView1.Rows[0].Cells[0].Text = "No Records Found";
}
 

Answers (2)