Vincent
Vincent

Reputation: 1477

ArgumentException when adding row to grid with DataGridViewComboBoxColumn

So I have a simple Grid on a WinForms app called dgAttributes. I use the following code to set up the columns:

dgAttributes.Columns.Clear();
dgAttributes.Columns.Add("Path", "Path");
dgAttributes.Columns.Add("Parameter", "Parameter");
DataGridViewComboBoxColumn comboBoxColumn = new DataGridViewComboBoxColumn
{
        HeaderText = "DataConnection",
        Name = "DataConnection",
        DisplayMember = "ConnectionName",
        ValueMember = "ServerName",
        DataSource = _dataConnections
};
dgAttributes.Columns.Add(comboBoxColumn);
dgAttributes.Columns.Add("Tag", "Tag");

The _dataConnections variable contains a list of DataConnections and is always populated with at least one valid instance. I want the ConnectionName to be displayed in the Grid. The DataConnection class looks like this:

public class DataConnection
{
    public string ServerName;
    public string UserName;
    public string ConnectionName;
    public override string ToString()
    {
        return ConnectionName;
    }
}

But when I try to do the following:

DataConnection conn = _dataConnections.DefaultIfEmpty(_dataConnections.FirstOrDefault())
                        .FirstOrDefault(a => a.ConnectionName == point.DataConnection);
dgAttributes.Rows.Add(point.RelativePath, point.Element.Name, conn, point.Tag);

I get an ArgumentException (without InnerException) on the second line stating:

Field called ConnectionName does not exist.

Could someone tell me what I'm doing wrong? I think it's something very obvious but I really can't seem to figure it out. And I did look at examples and other posts but it looks like I'm doing the right thing.

Upvotes: 0

Views: 1206

Answers (2)

Dattatraya Bhat
Dattatraya Bhat

Reputation: 21

For me, Setting DatagridView's "AutoSizeColumnsMode" value to "All cells" will give this error and setting the value back to "None" solved the problem

Upvotes: 0

Vincent
Vincent

Reputation: 1477

It turned out that the information from MSDN should be taken very literally:

then the DisplayMember property must be set to the necessary property name or column name.

Where "property" is the keyword here. Fields will not work. Thus after changing the string fields to properties, all was well. I must say that the Exception message is pretty missleading. And I hope this saves someone, somewhere, some head scratching.

(source: http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewcomboboxcolumn.displaymember%28v=vs.110%29.aspx)

Upvotes: 2

Related Questions