问题
In a C# WinForms project I am populating a DGV from a DataTable
. When a user clicks on the cell of one of the columns I need to populate a ComboBox
and open it on one click.
However the CBO will only open when the cell in question loses focus (click somewhere else on the form) and then gets focus back (click in that cell again) - and only if the CBO's down arrow is clicked, not if the CBO's text is clicked. I also need the CBO to open when the CBO's text is clicked.
private void dgvCategories_Click(Object sender, DataGridViewCellEventArgs e)
{
try
{
// Prevent code from executing if user clicks on a cell that already has a CBO
if (e.ColumnIndex == 5 && !(dgvCategories.Rows[e.RowIndex].Cells[e.ColumnIndex].GetType().Name == "DataGridViewComboBoxCell"))
{
// Get fields to build New Value query
List<string> lsNewValuesResult = new List<string>();
string strCategory = dtCategories.Rows[e.RowIndex][1].ToString();
string strCompanyName = cboSelectCompany.Text;
string strQueryGetNewValuesValidationInfo = "SELECT validationdb, validationtable, validationfield, validationfield2, validationvalue2" +
" FROM masterfiles.categories" +
" WHERE category = @category";
// Pass validation info query to db and return list of New Values
db getListOfNewValues = new db();
lsNewValuesResult = getListOfNewValues.GetNewValuesList(strQueryGetNewValuesValidationInfo, strCategory, strCompanyName);
// Create CBO object
DataGridViewComboBoxCell cboNewValueList = new DataGridViewComboBoxCell();
//Populate the combobox with the list of New Values
foreach (string strListItem in lsNewValuesResult) cboNewValueList.Items.Add(strListItem);
// Bind the CBO to the DGV
dgvCategories[e.ColumnIndex, e.RowIndex] = cboNewValueList;
var editingControl = dgvCategories.EditingControl as DataGridViewComboBoxEditingControl;
if (editingControl != null) editingControl.DroppedDown = true;
}
}
catch (Exception ex)
{
Console.WriteLine("dgvCategories_Click Exception: " + ex.Message);
}
}
DataGridViewEditMode
is set to EditOnEnter
and DataGrieViewSelectionMode
is set to CellSelect
.
The two lines at the end are from the SO Question, "DataGridViewComboBoxColumn - Have to click cell twice to display combo box"
I'm not sure what else to try...
来源:https://stackoverflow.com/questions/61232746/combobox-added-programmatically-to-datagridview-doesnt-open-until-after-the-cel