Click to See Complete Forum and Search --> : DataGridView/BindingSource missing IDs


DHarman
February 15th, 2010, 10:06 AM
I'm seeing an interesting issue with using a DataGridView tied to a BindingSource. Here's my scenario:

I have a table in a database/dataset that contains an autoincrement ID column and some other data columns (Name, address, etc). I then have a DataGridView that is bound to that dataset's datatable like this:


dataGridVolunteers.DataSource = tblVolunteersBindingSource;


As long as the ID field is sequential with no missing values the grid populates and selects the current record fine. However, I deleted the first 2 entries in the table which left 6 records with ID values 3-8 respectively.

Now, when my form loads, the current volunteer is ID 7 (Joe) which is record number 5 (index 4) in the binding source. The problem is, when I try to set the position in the binding source I get weird results.

Here's some sample data just to try and make it clearer:
ID Name Binding Source Index
3 Don 0
4 Penny 1
5 Jane 2
6 John 3
7 Joe 4
8 Josh 5
To set the current record in the binding source which should select it in the grid, I did this:

int idx = tblVolunteersBindingSource.Find("ID", iLastVolunteerID); //iLastVolunteerID = 7
tblVolunteersBindingSource.Position = idx;


When this code executes, Position ends up being 4 denoting index 4 in the binding soure which is correct...that's Joe. However, the item selected in the grid is Penny - who happens to have ID = 4.

So I thought maybe the position used the ID instead of the index in the binding source so I just set position=iLastVolunteerID and it sets the position to 5. That's because there are only 6 records in the binding source, so 7 is an invalid index and it defaults to the last index of 5 which causes Jane to be selected in the grid.

How can I make the binding source have it's current record as Joe and also select Joe in the grid?

Thanks!

DHarman
February 17th, 2010, 04:14 PM
The problem actually had nothing to do with the missing ID's...I was mistaken in my original post that with all the records there it worked correctly. Turns out the problem was actually with the way I was populating the datagridview.

The datagridview is bound to a bindingsource. In the Form_Load event I was manually setting the visible property for each column...except one...to false. The primary key is the ID field, the datagridview was showing only the "Name" field. The problem was the ID field was being hidden before the binding completed so the datagridview couldn't find the correct record.

To fix the issue, I now set all the columns to visible=false in Form_Load except ID and Name. Then, I add the datagridview_DataBindingComplete event and set the ID column's Visible=false in there. It works perfect now for both complete data and data with "skipped" ID values.