In my database web application, I am trying to add data to a column in gridView from a SQL table using the following code snippet
public void GetRowHeaders(GridView gridViewSample)
{
string commandstr = @"SELECT ID FROM WhiteBoardTest WHERE ID!=0 ORDER BY ID";
SqlCommand rowHeaderCmd = new SqlCommand(commandstr, sqlcon);
sqlcon.Open();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = rowHeaderCmd;
da.Fill(dt);
for (int i = 0; i < dt.Columns.Count; i++)
{
for (int j = 0; j < dt.Rows.Count; j++)
{
gridViewSample.Rows[0].Cells[j].Text = dt.Rows[j][i].ToString();
}
}
sqlcon.Close();
}
When I ran the above code, I got the error saying
ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection
I understand that the exception has occurred because the gridView has no rows or columns available.
Can anyone suggest me how to add rows to a column and also I am not using SqlDataSource because I would like add one more column to the gridView from a different table.