[C#] DataGridView ComboBox 欄位設定自動完成

解法來源:
AutoComplete ComboBox in DataGridView using C#.net Windows Application

需求:
DataGridView 的下拉選單欄位,可使用自動完成功能

問題:
遭遇 DataGridViewComboBoxColumn 沒有 ComboBoxStyle.DropDown 等屬性可設定的問題,
也無法轉型為 ComboBox 或 DataGridViewComboBoxEditingControl

解決方式:
設定DataGridView 的 EditingControlShowing 事件

 
private void dataGridView_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
 if (e.Control is DataGridViewComboBoxEditingControl)
 {
  ((ComboBox)e.Control).DropDownStyle = ComboBoxStyle.DropDown;
  ((ComboBox)e.Control).AutoCompleteSource = AutoCompleteSource.ListItems;
  ((ComboBox)e.Control).AutoCompleteMode = AutoCompleteMode.SuggestAppend;
 }
}

疑問:
為什麼 DataGridViewComboBoxColumn 無法強制轉型為 DataGridViewComboBoxEditingControl,
卻可以用 is DataGridViewComboBoxEditingControl 判斷後強轉為 ComboBox?

※註
DataGridViewComboBoxColumn 繼承自 DataGridViewColumn
 
public class DataGridViewComboBoxColumn : DataGridViewColumn
{
    ...
}

DataGridViewComboBoxEditingControl 繼承自 ComboBox
 
public class DataGridViewComboBoxEditingControl : ComboBox, IDataGridViewEditingControl
{
    ...
}

留言