Showing posts with label WinForms. Show all posts
Showing posts with label WinForms. Show all posts
Thursday, October 01, 2009
Friday, September 18, 2009
How to make the DataGridViewComboBoxCell actually behave like one
Even though the DataGridViewComboBoxColumn has a property for DisplayStyle which can be set to either DropDownButton or ComboBox (or Nothing), there's virtually no difference that I can see between the two settings. What I want is to be able to type text into the control like a normal ComboBox. I was disappointed to find out that this functionality is not built in. But after some struggle tracking it down (which is why I'm posting this), I did find some information about how you can actually make it work (kind of). These are the key events:
private void dataGridView1_EditingControlShowing(object sender,
DataGridViewEditingControlShowingEventArgs e)
{
ComboBox cbo = e.Control as ComboBox;
if (cbo != null) {
cbo.DropDownStyle = ComboBoxStyle.DropDown;
cbo.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
cbo.AutoCompleteSource = AutoCompleteSource.ListItems;
cbo.TextChanged -= new EventHandler(cbo_TextChanged);
cbo.TextChanged += new EventHandler(cbo_TextChanged);
}
}
private void dataGridView1_CellValidating(object sender,
DataGridViewCellValidatingEventArgs e)
{
object eFV = e.FormattedValue;
DataGridViewComboBoxCell cbc = dataGridView1.CurrentCell as
DataGridViewComboBoxCell;
if (cbc != null && !cbc.Items.Contains(eFV))
{
cbc.Items.Insert(0, eFV);
}
if (dataGridView1.IsCurrentCellDirty)
{
dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
cbc.Value = cbc.Items[0];
}
private void cbo_TextChanged(object sender, EventArgs e)
{
dataGridView1.NotifyCurrentCellDirty( true );
}
Labels:
.Net,
C#,
Programming,
VisualStudio,
WinForms,
Work
Subscribe to:
Posts (Atom)