0

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?

3
  • what is the data type of the rows that you are trying to add.. do you need to perhaps do some casting..? it's hard to tell what your structure is based on that little bit of code.. Commented Apr 5, 2013 at 20:36
  • I've updated the code to show everything relevant. Does this help? Commented Apr 5, 2013 at 20:45
  • 1
    instead of trying to do the row based on the Index try something like this dgvCrsLookupResults.Rows.Add(row["COLUMN_NAME"].ToString()); Replace COLUMN_NAME with the actual Column Name.. never rely on Indexes uses the actual Name Commented Apr 5, 2013 at 20:48

1 Answer 1

1

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;

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.