0
votes

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.

2

2 Answers

1
votes

I would just include the extra column in your select statement and just bind to the gridview - unless there's a specific reason for not doing that. note the new sql!

public void GetRowHeaders(GridView gridViewSample)
{
    string commandstr = @"SELECT a.*, b.somecolumn FROM tablea as a inner join tableb as b on b.someid= a.someid 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);

    gridViewSample.DataSource = dt;
    gridviewSample.DataBind();

    sqlcon.Close();
}

Or you could populate a collection of some class ( remember to use properties for gridviews databind), a List maybe, and just databind that to the grid.

1
votes

Dayakar, what you can do is add additional column and data to DataTable itself and then bind it to the gridview. below is a example code.

private void SetupGridView()
{
    var dt = GetDataTable();

    // add addition column
    dt.Columns.Add(new DataColumn() {ColumnName = "Id2", DataType = typeof (int)});

    // add additional data
    for (var i = 0; i < dt.Rows.Count; i++)
    {
        dt.Rows[i]["Id2"] = Convert.ToInt32(dt.Rows[i][0])*2;
    }

    GridView1.DataSource = dt;
    GridView1.DataBind();
}

You can also merge two datatables to create one datatable and then bind it to gridview. Refer http://msdn.microsoft.com/en-us/library/fk68ew7b.aspx