Kulahan
Kulahan

Reputation: 522

adding datarow to datagridview only adding to first column

I'm trying to pull a set of data from a database and shove it in to a datagridview. Problem is, when I do this, I get "system.data.datarow", and it only adds it to the first column (I've got 5). Here's my code.

SqlCommand sqlCom = new SqlCommand("some SQL query string", "SQL database connection info");
SqlDataAdapter adapter = new SqlDataAdapter(sqlComm);
DataTable table = new Datatable();

if (methodType = "SELECT")
{
    sqlConn.Open();
    adapter.fill(table);
    foreach (DataRow row in table.Rows)
    {
        dgvCrsLookupResults.Rows.Add(row[0]);
        dgvCrsLookupResults.Rows.Add(row[1]);
        dgvCrsLookupResults.Rows.Add(row[2]);
        dgvCrsLookupResults.Rows.Add(row[3]);
        dgvCrsLookupResults.Rows.Add(row[4]);
    }
}

Obviously, this only fills in the first column, but I can't figure out for the life of me how to add it to each column instead. When I use

dgvCrsLookupResults.Columns.Add(row[0]);

It just says that it has invalid arguments. I know I'm damn close, but I'm new to all of this, so I'm completely lost as to how to make that last jump. Thoughts?

Upvotes: 0

Views: 2658

Answers (1)

Fabio
Fabio

Reputation: 32445

Instead of looping foreach(DataRow row in table.Rows) use:

dgvCrsLookupResults.DataSource = table;

Remember set:

dgvCrsLookupResults.AutoGenerateColumns = True;

Or in designer create a columns for your DataGridView.

In column set DataPropertyName = ColumnName in DataTable

In this case -> dgvCrsLookupResults.AutoGenerateColumns = False;

Upvotes: 1

Related Questions