AutoCompleteStringCollection for text box in DataGridView 2.0

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I have been searching for a way to have autocomplete in a DataGridTextBox
object. There does not appear to be an obvious way to do this like you would
for a TextBox outside of a grid using the AutoCompleteCustomSource. Any
thoughts on how I can add this collection? :)
 
It's actually pretty easy (although as far as I know no one has posted
this code yet). Someone please let me know if this is the wrong way of
doing it:

Just listen for the EditingControlShowing event of the DataGridView.
This will give you a chance to mess with the cell before it allows the
user to edit.

In this case, I did the following:

private void m_Grid_EditingControlShowing(object sender,
DataGridViewEditingControlShowingEventArgs e)
{
if (e.Control is DataGridViewTextBoxEditingControl)
{
DataGridViewTextBoxEditingControl te =
(DataGridViewTextBoxEditingControl)e.Control;
te.AutoCompleteMode = AutoCompleteMode.Append;
te.AutoCompleteSource = AutoCompleteSource.CustomSource;
te.AutoCompleteCustomSource.AddRange(new string[] {"one", "two",
"three"});
}
}

This works because DataGridViewTextBoxEditingControl is just a
subclassed TextBox.

Hope this helps.
 
The only change I made was to be specific about the autocomplete information
for each column.


private void dataGridView_fish_EditingControlShowing(object sender,
DataGridViewEditingControlShowingEventArgs e)
{
if (e.Control is DataGridViewTextBoxEditingControl)
{
DataGridViewTextBoxEditingControl te =
(DataGridViewTextBoxEditingControl)e.Control;
te.AutoCompleteMode = AutoCompleteMode.Append;
te.AutoCompleteSource = AutoCompleteSource.CustomSource;

DataGridView dgv = (DataGridView)sender; //reference to the
original grid
int col = dgv.CurrentCell.ColumnIndex; //columnindex if the
current cell

switch (col) //check for each col (column number) and set
the autocomplete for it
{
case 0: // column 0
te.AutoCompleteCustomSource.AddRange(new string[]
{"abc", "def", ghi"});
break;
case 1:
te.AutoCompleteCustomSource.AddRange(new string[]
{"jkl", "mno", "pqr"});
break;

default:
break;
}
 
Back
Top