views:

39

answers:

4

I am new to windows application. I need to add rows in the DataGrid dynamically which has person data. when i do the following is see only the last person in the last row. i see rows populating but with no data. If i do a break on the first fetch i do get the right one. But something is wrong. Any ideas

foreach (var p in personList)
        {

            gvAdminSummary.Rows.Add(new DataGridViewRow());
            gvAdminSummary.Rows[gvAdminSummary.Rows.Count-1].Cells[0].Value = p.FName;
            gvAdminSummary.Rows[gvAdminSummary.Rows.Count - 1].Cells[1].Value = p.LName;
            gvAdminSummary.Rows[gvAdminSummary.Rows.Count - 1].Cells[2].Value = p.PNo;


        }
A: 

This may not be the right approach. Create a BindingSource and bind a collection of your objects to it. Then bind the BindingSource to the Grid's data source. Make sure your objects implement INotifyPropertyChanged. This way, whenever, you add an object to the collection, or change a property within your object, it'll automatically reflect in the grid.

AngryHacker
+1  A: 

The DataGridRowView.Add method accepts string arrays:

gvAdminSummary.Rows.Add( { p.FName, p.LName, p.PNo });

Likely, though, there's a better solution for you in binding the grid directly to your person list.

xcud
A: 

I don't know about DataGridView, but if you want to stick to inserting data into the control directly, why not use ListView instead? It has an API more suited to your current needs or way of doing things.

Daniel Mošmondor
A: 

Either

gvAdminSummary.Datasource = persons; gvAdminSummary.databind();

Or

foreach (var p in personList) { DataGridViewRow dr = new DataGridViewRow(); dr.cells.add(new datagridcell()) etc.. populate cells gvAdminSummary.Rows.add(dr);

    }
Poker Villain