I have a class called Contacts which contains a collection of objects called PhoneNumbers. Each PhoneNumbers object has several properties including PhoneNumber and PhoneType as well as the foreign key PhoneTypeFK. I assign this collection to a DataGridView control’s DataSource and hide the columns (properties) I don’t want to see in the DGV. This creates a bunch of text cells (rows/cols) in the DGV being for the Phone Number and the Type. All well and good except, I want a combobox to be shown in the Phone Type column populated with all the various Phone Types of the PhoneTypes Table with the appropriate Phone Type shown in the cell for that Phone Number.
I read somewhere that I need to add a combobox column at design time with the same DataPropertyName as the Property of the PhoneNumbers Object, i.e. PhoneType so that when the DGV is populated with columns it will use this column instead of creating a new one (for the PhoneType). I cannot, however, get this to work.
I used the code below to populate the DGV and hide the irrelevant columns:
//Fill Grid
uxContactPhoneNumbersGrd.DataSource = contacts.PhoneNumbers;
//Hide non-required columns/rows
uxContactPhoneNumbersGrd.RowHeadersVisible = false;
string[] columnNamesToHide = { "ErrMsg", "ContactsFk", "PhoneNumbersPk", "PhoneTypesFk" };
SAPSCommon.Instance.HideGridColumns(ref uxContactPhoneNumbersGrd, columnNamesToHide);
When I do this, I get 2 columns for the PhoneType, one is the text cell created when populating the DGV, the other is the combobox column I added at design time (even though it has the same DataPropertyName as suggested).
How do I get only 1 column for PhoneType and how do I bind it to the PhoneTypes Table so that the data from the PhoneNumbers Objects sets the correct PhoneType for the respective PhoneNumber?
(Do I need to bind the PhoneType combobox column 1st before populating the grid with the PhoneNumbers Objects?)
OK, so after MANY hours of trial and error I seem to have found a solution.
The basic process is to:
The reason I name the DataPropertyName of the grid columns to be the same as the PhoneNumber object Property names is so that the grid automatically populates the correct columns with the data from the list of PhoneNumber objects. Disabling AutoGenerateColumns ensures only the named columns are populated, i.e. the grid does not automatically generate columns for the other properties of the PhoneNumber objects which are not required for this application.
This is the PhoneNumber class which is used to create a list of PhoneNumber objects in the Contacts object:
}
This is the code that populates the DataGridView control:
I hope this helps some other poor soul out there trying to make the DataGridView control display data from an object using a support table…