Okay, let's optimize your DataGridViewEx control. The main issues are:
- Delayed Update: The cell doesn't refresh immediately after selection. This is because the
DataGridView doesn't know the cell's value has programmatically changed in a way it expects during an edit operation. We need to properly notify it.
- Dropdown Not Showing: This can be due to focus issues, the ComboBox being obscured, or timing problems with setting
DroppedDown = true.
- Editor Persistence/Cleanup: We need to ensure the editor is closed if the user scrolls, clicks another cell, or the grid loses focus.
- Better User Experience: Committing on
SelectionChangeCommitted for immediate feedback.
Here's an improved version:
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Drawing; // Required for Rectangle
namespace Tab.Library
{
public class DataGridViewEx : DataGridView
{
private readonly Dictionary<int, List<string>> _comboBoxItems = new();
private ComboBox? _editorComboBox; // Make nullable
private int _currentRowIndex = -1;
private int _currentColIndex = -1;
private bool _isEditingComboBox = false; // Flag to track editing state
public DataGridViewEx()
{
// Subscribe to events that should close the editor
this.Scroll += DataGridViewEx_Scroll;
this.CellBeginEdit += DataGridViewEx_CellBeginEdit; // If user clicks another editable cell
this.SelectionChanged += DataGridViewEx_SelectionChanged; // If selection moves away
}
// Ensure events are unsubscribed when the control is disposed
protected override void Dispose(bool disposing)
{
if (disposing)
{
this.Scroll -= DataGridViewEx_Scroll;
this.CellBeginEdit -= DataGridViewEx_CellBeginEdit;
this.SelectionChanged -= DataGridViewEx_SelectionChanged;
CloseEditor(false); // Ensure editor is cleaned up
}
base.Dispose(disposing);
}
private void DataGridViewEx_SelectionChanged(object? sender, EventArgs e)
{
// If selection changes away from the editing cell, close the editor
if (_isEditingComboBox && this.CurrentCell != null &&
(this.CurrentCell.RowIndex != _currentRowIndex || this.CurrentCell.ColumnIndex != _currentColIndex))
{
// Only save if the ComboBox still has focus, otherwise it might be due to programmatic selection change
// A more robust way might be needed if SaveAndCloseEditor() is desired here
CloseEditor(false);
}
}
private void DataGridViewEx_CellBeginEdit(object? sender, DataGridViewCellCancelEventArgs e)
{
// If our custom editor is open and the grid tries to edit another cell, close our editor.
if (_isEditingComboBox && (e.RowIndex != _currentRowIndex || e.ColumnIndex != _currentColIndex))
{
CloseEditor(false); // Don't save, user is explicitly moving away
}
}
private void DataGridViewEx_Scroll(object? sender, ScrollEventArgs e)
{
// If scrolling occurs while editor is open, close it
if (_isEditingComboBox)
{
CloseEditor(false); // Typically, scrolling aborts an edit
}
}
public void SetComboBoxColumn(int columnIndex, List<string> items)
{
if (columnIndex < 0) throw new ArgumentOutOfRangeException(nameof(columnIndex));
_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;
// Check if this cell is already being edited by our ComboBox
if (_isEditingComboBox && _currentRowIndex == e.RowIndex && _currentColIndex == e.ColumnIndex)
{
return; // Already editing this cell
}
// If another cell was being edited, close that first
if (_isEditingComboBox)
{
CloseEditor(true); // Attempt to save previous edit
}
if (_comboBoxItems.TryGetValue(e.ColumnIndex, out var items))
{
_currentRowIndex = e.RowIndex;
_currentColIndex = e.ColumnIndex;
// Important: Notify the DataGridView that an edit is beginning
// This helps with focus management and prevents default editors from appearing.
this.BeginEdit(true);
ShowComboBoxEditor(items);
}
}
private void ShowComboBoxEditor(List<string> items)
{
if (_editorComboBox != null) // Should ideally be cleaned up by CloseEditor
{
CleanUpEditor();
}
_isEditingComboBox = true;
_editorComboBox = new ComboBox
{
DropDownStyle = ComboBoxStyle.DropDown, // Allows typing
FlatStyle = FlatStyle.Flat,
AutoCompleteMode = AutoCompleteMode.SuggestAppend, // Good for usability
AutoCompleteSource = AutoCompleteSource.ListItems
};
_editorComboBox.Items.AddRange(items.ToArray());
Rectangle rect = GetCellDisplayRectangle(_currentColIndex, _currentRowIndex, false); // Use false for non-header cells
_editorComboBox.Bounds = rect;
// Set current value
var cellValue = this[_currentColIndex, _currentRowIndex].Value;
_editorComboBox.Text = cellValue?.ToString() ?? "";
_editorComboBox.Leave += EditorComboBox_Leave;
_editorComboBox.KeyDown += EditorComboBox_KeyDown;
_editorComboBox.SelectionChangeCommitted += EditorComboBox_SelectionChangeCommitted;
_editorComboBox.LostFocus += EditorComboBox_LostFocus; // Handles clicking outside the DGV
Controls.Add(_editorComboBox);
_editorComboBox.BringToFront(); // Ensure it's on top
_editorComboBox.Focus(); // Give it focus
// Delay DroppedDown to ensure the control is fully initialized and visible
// This can sometimes help with the dropdown not appearing reliably.
this.BeginInvoke(new Action(() => {
if (_editorComboBox != null && !_editorComboBox.IsDisposed)
{
_editorComboBox.DroppedDown = true;
}
}));
}
private void EditorComboBox_LostFocus(object? sender, EventArgs e)
{
// If the ComboBox loses focus to something that isn't the DataGridView itself
// or one of its children (like scrollbars), it means focus went outside.
// However, the Leave event is generally more reliable for committing.
// This can be tricky. If focus goes to another control on the form, Leave should fire.
// If DGV itself gets focus (e.g. clicking another cell), our DGV events handle it.
}
private void EditorComboBox_SelectionChangeCommitted(object? sender, EventArgs e)
{
// User selected an item from the list, commit immediately
SaveAndCloseEditor();
}
private void EditorComboBox_KeyDown(object? sender, KeyEventArgs e)
{
if (_editorComboBox == null) return;
switch (e.KeyCode)
{
case Keys.Enter:
SaveAndCloseEditor();
e.Handled = true;
e.SuppressKeyPress = true; // Prevent ding sound
break;
case Keys.Escape:
CloseEditor(false); // Don't save on Escape
e.Handled = true;
e.SuppressKeyPress = true;
break;
case Keys.Tab:
SaveAndCloseEditor();
// Allow tab to naturally move to the next control/cell
// DataGridView handles Tab key navigation if editor is properly closed.
break;
}
}
private void EditorComboBox_Leave(object? sender, EventArgs e)
{
// If the editor loses focus, and it's not because it's being disposed,
// save the changes. This handles clicking away.
if (_isEditingComboBox && _editorComboBox != null && !_editorComboBox.Disposing && !_editorComboBox.IsDisposed)
{
// Check if focus is moving to a child of the DGV or the DGV itself.
// If so, our other DGV event handlers might take care of it.
// However, a simple approach is to always try to save.
SaveAndCloseEditor();
}
}
private void SaveAndCloseEditor()
{
if (!_isEditingComboBox || _editorComboBox == null) return;
// Update cell value
this[_currentColIndex, _currentRowIndex].Value = _editorComboBox.Text;
// Important: Notify DataGridView about the change and end editing
// This is crucial for the value to be committed and display updated.
this.NotifyCurrentCellDirty(true); // Mark cell as dirty
this.EndEdit(); // Commit the edit
CloseEditor(false); // Close without trying to save again
}
private void CloseEditor(bool attemptSaveBeforeClosing)
{
if (attemptSaveBeforeClosing && _isEditingComboBox && _editorComboBox != null)
{
// This call to SaveAndCloseEditor will itself call CloseEditor(false)
// so we need to be careful not to get into a loop or double dispose.
// The _isEditingComboBox flag helps.
SaveAndCloseEditor();
return; // SaveAndCloseEditor will handle the cleanup.
}
if (_editorComboBox != null)
{
CleanUpEditor();
}
// If the DGV is still in edit mode for this cell, ensure it ends.
if (this.IsCurrentCellInEditMode &&
this.CurrentCell != null &&
this.CurrentCell.RowIndex == _currentRowIndex &&
this.CurrentCell.ColumnIndex == _currentColIndex)
{
this.EndEdit();
}
// Reset state
_isEditingComboBox = false;
_currentRowIndex = -1;
_currentColIndex = -1;
// It's good practice to return focus to the grid
if (this.Focused == false && this.Parent != null && this.Parent.ContainsFocus)
{
// Only focus if the parent form/container still has focus
// to avoid stealing focus if the whole app lost focus
// this.Focus(); // This might be too aggressive sometimes.
}
}
private void CleanUpEditor()
{
if (_editorComboBox != null)
{
_editorComboBox.Leave -= EditorComboBox_Leave;
_editorComboBox.KeyDown -= EditorComboBox_KeyDown;
_editorComboBox.SelectionChangeCommitted -= EditorComboBox_SelectionChangeCommitted;
_editorComboBox.LostFocus -= EditorComboBox_LostFocus;
if (Controls.Contains(_editorComboBox))
{
Controls.Remove(_editorComboBox);
}
_editorComboBox.Dispose();
_editorComboBox = null;
}
}
}
}