我在向DataGridView中添加DataGridViewComboBoxColumn时遇到了一些奇怪的行为。这是我的代码:
private void CreateSupplyTypeColumn()
{
supplyTypeCombo = new DataGridViewComboBoxColumn();
supplyTypeCombo.HeaderText = "Circuit Type";
supplyTypeCombo.Name = "colCircuitType";
supplyTypeCombo.DataSource = supplyType;
supplyTypeCombo.DisplayMember = "SupplyTypeShort";
supplyTypeCombo.ValueMember = "SupplyTypeID";
dgDeliveryPoints.Columns.Insert(4, supplyTypeCombo);
}
private void btnSearch1_ByIsCurrent(object sender, EventArgs e)
{
dgDeliveryPoints.DataSource = null
dgDeliveryPoints.DataSource = dpResult;
if (!dgDeliveryPoints.Columns.Contains(supplyTypeCombo))
CreateSupplyTypeColumn();
else
supplyTypeCombo.DisplayIndex = 4;
foreach (DataGridViewRow row in dgDeliveryPoints.Rows)
row.Cells[4].Value = row.Cells["SupplyTypeID"].Value;
}
我第一次按下搜索按钮时,btnSearch1_ByIsCurrent方法触发,supplyTypeCombo看起来不错。 它在 dgDeliveryPoint 网格中正确定位,并且具有正确的值,但当我再次按下搜索按钮时,我会出现奇怪的行为。当我再次按下按钮时,supplyTypeCombo 列的索引从 4 变为 3??为什么会这样?另外,我有这个代码的原因:
if (!dgDeliveryPoints.Columns.Contains(supplyTypeCombo))
CreateSupplyTypeColumn();
else
supplyTypeCombo.DisplayIndex = 4;
这是因为即使我通过每次单击按钮将数据源清空到 dgDeliveryPoint 以重新设置所有内容并尝试重新添加 supplyTypeCombo 列,我也会收到一个异常,说明它已经存在。为什么会这样??
您是否尝试过更改此行代码:
row.Cells[4].Value = row.Cells["SupplyTypeID"].Value;
对此:
supplyTypeCombo.DataPropertyName = "SupplyTypeID";