views:

523

answers:

2

How do I add rows programmatically to a DataGridTable in C#? When the user selects an option, I want to repopulate a DataGridTable with fresh data, which I am acquiring as shown below:

        connect.Open();
        MySqlCommand comm = connect.CreateCommand();
        comm.CommandText = getCustomerInvoices + customerID + "\'";
        MySqlDataReader r = comm.ExecuteReader();
        while (r.Read())
        {
            DataGridViewRow d = new DataGridViewRow();
            String[] parameters = new String[5];
            parameters[0] = r.GetValue(0).ToString();
            parameters[1] = r.GetValue(1).ToString();
            parameters[2] = r.GetValue(2).ToString();
            parameters[3] = r.GetValue(3).ToString();
            parameters[4] = r.GetValue(4).ToString();
            d.SetValues(parameters);
            invoiceTable.Rows.Add(d);
        }
        connect.Close();

What seems to happen is that I get a new row added to the table, but the old rows are still there, and the new row does not appear to have any values in it (a bunch of blank textboxes, and I know that this query is returning one result in my test case).

Can someone explain to me what I have to do?

+1  A: 

I believe Rows.Add() has an overload for an array of strings. If you are creating an array of strings anyways, why not try using it? i.e. instead of:

d.SetValues(parameters);
invoiceTable.Rows.Add(d);

you would juse use:

invoiceTable.Rows.Add(parameters);

Alternatively, if you still want to create a DataGridViewRow object and call setvalues on it, I think you need to either cast the array to an array of type Object, or pass each value as it's own argument instead of passing the array.

Drakonite
Thanks, I didn't know about the overloaded version. It works now.
Elie
A: 

I believe you need to call .CreateCells(GridName) before you call setvalue

pyrokin5