DataGridView ComboBox永远不会填充

时间:2011-04-18 05:25:37

标签: c# winforms data-binding datagridview datagridcomboboxcolumn

我在DataGridView中有一个ComboBox的列,我无法填充它。我一遍又一遍地查看我的代码,看起来是对的,但不能因为ComboBox从未填充过。

这是我的代码。

首先,用于测试的静态数据源:

List<Phone> PhoneList = new List<Phone>();

Phone p1 = new Phone();
p1.PhoneID = 1;
p1.PhoneTypeID = 2;
p1.AreaCode = "333";
p1.Number = "123-1234";
p1.PhoneTypeName = "Primary";
PhoneList.Add( p1 );

Phone p2 = new Phone();
p2.PhoneID = 2;
p2.PhoneTypeID = 2;
p2.AreaCode = "444";
p2.Number = "432-8900";
p2.PhoneTypeName = "Secondary";
PhoneList.Add( p2 );

这只是为了显示ComboBox列的DataPropertyName:

this.dgvClinic.Columns[ "PhoneName" ].DataPropertyName = "PhoneID";

接下来,我正在提取数据,然后对于每一行,我向DataGridView添加一行并为新添加的行填充单元格。最后是我的ComboBox专栏,正如您所看到的,我正在填充我的DataSource,DisplayMember和ValueMember属性。请注意最后三行注释掉的行,因为我甚至尝试将静态值添加到单元格的Item集合中。两种方法都不奏效。所有这一切都是前三列有数据,但ComboBox单元格从不有任何数据。

Clinic c = new Clinic();
string CurrentLocation = string.Empty;
foreach ( Clinic i in c.SelfListAll() )
{
    Location_List_ByClinicResult l = i.Locations.FirstOrDefault<Location_List_ByClinicResult>();
    if ( l == null )
    {
        CurrentLocation = "12345 Main Street" + " " + "San Rafael" + ", " + "CA" + " " + "94903";
    }
    else
    {
        CurrentLocation = l.Address1 + " " + l.City + ", " + l.StateAbbrev + " " + l.Zip;
    }

    RowIndex = this.dgvClinic.Rows.Add();

    this.dgvClinic.Rows[ RowIndex ].Cells[ "ClinicID" ].Value = i.ClinicID.ToString();
    this.dgvClinic.Rows[ RowIndex ].Cells[ "ClinicName" ].Value = i.Name;
    this.dgvClinic.Rows[ RowIndex ].Cells[ "LocationName" ].Value = CurrentLocation;

    DataGridViewComboBoxCell cell = this.dgvClinic.Rows[ RowIndex ].Cells[ "PhoneName" ] as DataGridViewComboBoxCell;
    cell.DataSource = PhoneList;
    cell.DisplayMember = "Number";
    cell.ValueMember = "PhoneID";
    //cell.Items.Add( "One" );
    //cell.Items.Add( "Two" );
    //cell.Items.Add( "Three" );
}

我真的希望有人能看到我在这里失踪的东西。顺便说一下,我在设计师中创建了列。

感谢。

2 个答案:

答案 0 :(得分:0)

cell.DataSource = PhoneList;
cell.DisplayMember = "Number";
cell.ValueMember = "PhoneID";

看一下这部分,我可以观察到你将Phone列表设置为DataSource到cell。现在,DisplayMemberValueMember属性将在"Number"中查找列"PhoneID"PhoneList。但实际上PhoneList没有任何名为"Number""PhoneID"的列,而是PhoneList的子p1和p2具有这些列。因此,它无法在Datasource Phonelist中找到列("Number""PhoneID")。

尝试在数据表中填充它并将其分配给单元格。

DataTable dt = new DataTable();
//Add Row p1
//Add Row p2

现在分配它们。

  cell.DataSource = dt;
  cell.DisplayMember = "Number";
  cell.ValueMember = "PhoneID";

另见this link

答案 1 :(得分:0)

您是否尝试过像这样使用DataGridViewComboBoxColumn:

DataGridViewComboBoxColumn column = new DataGridViewComboBoxColumn();
column.DataSource = PhoneList;
column.DataPropertyName = "PhoneID";
column.MaxDropDownItems = 4;
column.DisplayStyle = DataGridViewComboBoxDisplayStyle.ComboBox;
yourdatagridview.Columns.Add(column);

也许它的工作原理是组合框应该包含datagridview中所有行的相同列表。至少你会知道当你为所有行使用一个PhoneList时它是否有效。