添加DataGridViewComboBoxColumn - 当网格刷新列的索引更改时

时间:2014-11-27 16:01:05

标签: c# datagridview

通过向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看起来很好。它正确定位在dgDeliveryPoints网格中,它具有正确的值,但当我再次按下搜索按钮时,我会遇到奇怪的行为。 当我再次按下按钮时,supplyTypeCombo列的索引从4变为3 ??为什么会发生这种情况?另外,我有这个代码的原因:

        if (!dgDeliveryPoints.Columns.Contains(supplyTypeCombo))
            CreateSupplyTypeColumn();
        else
            supplyTypeCombo.DisplayIndex = 4;

因为即使我使用每个按钮将数据源清空到dgDeliveryPoints,也可以单击以重新设置所有内容并尝试添加supplyTypeCombo列,但我得到一个例外,说明它已经存在。为什么会发生这种情况?

1 个答案:

答案 0 :(得分:0)

您是否尝试更改此行代码:

row.Cells[4].Value = row.Cells["SupplyTypeID"].Value;

到此:

supplyTypeCombo.DataPropertyName = "SupplyTypeID";