Question

I am working with C# 4.0 WinForms. I have a DataGridView which has all of it's columns set in the designer. The "Room" column is a DataGridViewComboBoxColumn column.

All of the cells show the correct information, including the Room Column. However, when I click on the DropDown for Room the items in the list show a quantity of rows which say System.Data.DataRowView instead of the actual value of the DisplayMember property.

My code looks like this:

DataTable dttRooms = GetDataTable();  //Returns rows with RoomID (GUID) and RoomType (string) columns
List<RoomType> roomType = new List<RoomType> { }; 
foreach (DataRow dr in dttRooms.Rows)
{
    roomType.Insert(roomType.Count, new RoomType { RoomID = Convert.ToString(dr["RoomID"]), RoomName = Convert.ToString(dr["RoomType"]) });
}

DataGridViewComboBoxColumn dgvc;
dgvc = (DataGridViewComboBoxColumn)dgvItems.Columns["Room"];
dgvc.HeaderText = "Room";
dgvc.DataPropertyName = "RoomID";
dgvc.DisplayMember = "RoomName";
dgvc.ValueMember = "RoomID";
dgvc.DataSource = roomType;

dgvItems.DataSource = dtForGridView; //dtForGridView contains a RoomID column with the GUID of the corresponding room.

I have defined a RoomType Class as below:

public class RoomType
{
    public string RoomID { get; set; }
    public string RoomName { get; set; }
}

If I change the room of an item in the database, it shows correctly on the GridView combobox column as expected.

I've set the DisplayMember and the ValueMember of the column. But when I pull the dropdown down to change the value, there's the correct number of rows, but they seem to be ignoring their DisplayMember property. I've been trying for quite some time to figure out what I am doing wrong. I have spent hours and hours on SO looking at all similar questions and tried pretty much everything.

Was it helpful?

Solution

I changed the name of my Class and the RoomName property to RoomType:

public class _RoomType
{
    public string RoomID { get; set; }
    public string RoomType { get; set; }
}

I changed my code so that the names all match up:

DataTable dttRooms = lda.RoomDetailsGet(SeriesID, JobID);
List<_RoomType> roomType = new List<_RoomType> { };
foreach (DataRow dr in dttRooms.Rows)
{
    roomType.Insert(roomType.Count, new _RoomType { RoomID = Convert.ToString(dr["RoomID"]), RoomType = Convert.ToString(dr["RoomType"]) });
}

DataGridViewComboBoxColumn dgvc;
dgvc = (DataGridViewComboBoxColumn)dgvItems.Columns["Room"];
dgvc.HeaderText = "Room";
dgvc.DataPropertyName = "RoomID";
dgvc.ValueMember = "RoomID";
dgvc.DisplayMember = "RoomType";
dgvc.DataSource = roomType;

dgvItems.DataSource = dtForGridView;

Suddenly it's working as expected. I'd still love to know why, but at least my problem is solved.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top