【发布时间】:2012-07-18 15:32:39
【问题描述】:
我有一个带有几个 DataGridViewComboBoxColumns 的 DataGridView。 DataGridView 上有一个 CellEnter 事件处理程序,用于单击下拉组合框。
该列绑定到一个 KeyValuePairs 列表,ValueMember 为“Key”,DisplayMember 为“Value”。
当我单击组合框列时,它工作正常。但是,如果单元格处于“下拉”状态并且我单击另一个组合框(同一列,不同行),它会正确取消选择旧单元格,选择并下拉新单元格,但是顶部的选定值会更改为旧单元格中的值一瞬间,然后改回正确的值。
例如,假设列表是 A、B、C。在第 1 行中,选择了 A,在第 2 行中,选择了 B。我单击 row1 中的单元格,一切正常。然后,当这个单元格被下拉时,我单击 row2 中的单元格。它正确下降,但顶部选定的值变为 A,然后立即切换回 B(正确的值)。
如果我在单击第二个组合框单元格之前单击其他列中的单元格,则不会发生这种情况。
有没有办法防止这种情况发生?
重现问题的示例代码(事件处理程序与明显的事件挂钩):
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace PDGV
{
public partial class Form1 : Form
{
List<KeyValuePair<string, string>> bindingList = new List<KeyValuePair<string, string>>();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.Rows.Add(10);
bindingList.Add(new KeyValuePair<string,string>("aaa", "111"));
bindingList.Add(new KeyValuePair<string,string>("bbb", "222"));
bindingList.Add(new KeyValuePair<string,string>("ccc", "333"));
bindingList.Add(new KeyValuePair<string,string>("ddd", "444"));
bindingList.Add(new KeyValuePair<string,string>("eee", "555"));
BindComboList(2, bindingList);
}
private void BindComboList(int columnIndex, object list)
{
var column = dataGridView1.Columns[columnIndex] as DataGridViewComboBoxColumn;
if (column != null)
{
column.DataSource = new BindingSource(list, null);
column.DisplayMember = "Value";
column.ValueMember = "Key";
}
}
private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex == -1)
return;
dataGridView1.BeginEdit(true);
var control = dataGridView1.EditingControl as DataGridViewComboBoxEditingControl;
if (control != null)
control.DroppedDown = true;
}
}
}
【问题讨论】:
-
不清楚您的问题是什么 - 我已尝试根据您的描述重新创建此内容,但无法复制您所描述的任何内容。请提供一个最小且完整的代码示例 - 最好从表单中复制此问题的代码(仅包含相关代码)。
-
我已经添加了代码。注意 - 必须通过单击打开组合框。我不能只删除此功能。
-
仍然不确定您的问题是什么 - 您能否将所有事件附加到代码后面,如果可能的话还添加列。目前尚不清楚您在设计器中所做的确切操作,因此在代码中进行更改的完全标准的 datagridview(只是拖到一个空表单上)会更容易遵循。然后我正在尝试解决您遇到的确切问题-如果我有两个组合单元格,并且都选择了值,那么我下拉一个单元格并选择第二个单元格-您说您暂时看到了第一个单元格中的选定值第二个细胞?我根本看不到。
-
罢工 - 终于设法看到你的问题是什么。
-
仍然在看这个 - 有一种可怕的感觉,你不走运。问题是当您在同一列中的单元格之间移动时,DataGridView 只有 1 个编辑控件实例。因此,有时您会看到最后一个单元格的值,因为它在更新控件之前会重绘控件。我试图找到一个事件来强制编辑控件及时重绘,但到目前为止还没有运气。顺便说一句 - 在 EditingControlShowing 事件中强制控件打开比在 CellEnter 事件中打开更好。
标签: c# datagridview