ComboBox added programmatically to DataGridView doesn't open until after the cell loses focus and then is clicked on again

ε祈祈猫儿з 提交于 2020-04-18 05:46:37

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!