using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace Tab.Library
{
public class DataGridViewEx : DataGridView
{
// 用列索引绑定下拉项列表
private readonly Dictionary<int, List> _comboBoxItems = new();
private ComboBox _editorComboBox;
private int _currentRowIndex;
private int _currentColIndex;
// 设置某列为下拉编辑列(支持手动输入)
public void SetComboBoxColumn(int columnIndex, List<string> items)
{
_comboBoxItems[columnIndex] = items ?? throw new ArgumentNullException(nameof(items));
}
protected override void OnCellDoubleClick(DataGridViewCellEventArgs e)
{
base.OnCellDoubleClick(e);
if (e.RowIndex < 0 || e.ColumnIndex < 0) return;
// 如果该列有下拉数据源,表示是 ComboBox 列
if (_comboBoxItems.TryGetValue(e.ColumnIndex, out var items))
{
_currentRowIndex = e.RowIndex;
_currentColIndex = e.ColumnIndex;
ShowComboBoxEditor(items);
}
}
private void ShowComboBoxEditor(List<string> items)
{
if (_editorComboBox != null)
{
Controls.Remove(_editorComboBox);
_editorComboBox.Dispose();
}
_editorComboBox = new ComboBox
{
DropDownStyle = ComboBoxStyle.DropDown,
FlatStyle = FlatStyle.Flat
};
_editorComboBox.Items.AddRange(items.ToArray());
var rect = GetCellDisplayRectangle(_currentColIndex, _currentRowIndex, true);
_editorComboBox.Bounds = rect;
_editorComboBox.Text = this[_currentColIndex, _currentRowIndex].Value?.ToString() ?? "";
_editorComboBox.Leave += (s, e) => SaveAndCloseEditor();
_editorComboBox.KeyDown += ComboBox_KeyDown;
Controls.Add(_editorComboBox);
_editorComboBox.Focus();
_editorComboBox.DroppedDown = true; // 自动展开
}
private void ComboBox_KeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Enter:
SaveAndCloseEditor();
e.Handled = true;
break;
case Keys.Escape:
CloseEditor();
e.Handled = true;
break;
}
}
private void SaveAndCloseEditor()
{
if (_editorComboBox == null) return;
this[_currentColIndex, _currentRowIndex].Value = _editorComboBox.Text;
CloseEditor();
}
private void CloseEditor()
{
if (_editorComboBox == null) return;
Controls.Remove(_editorComboBox);
_editorComboBox.Dispose();
_editorComboBox = null;
}
}
} 以上自定义控件,有时选择后不会更新显示,要点击其它cell后才显示,有时下拉菜单不显示,优化它