【发布时间】:2020-07-28 15:50:12
【问题描述】:
在 C# WinForms 项目中,我从 DataTable 填充 DGV。当用户单击其中一列的单元格时,我需要填充 ComboBox 并单击一次打开它。
但是,只有当相关单元格失去焦点(单击表单上的其他位置)然后重新获得焦点(再次单击该单元格)时,CBO 才会打开 - 并且只有在单击 CBO 的向下箭头时才会打开,如果CBO 的文本被点击。当点击 CBO 的文本时,我还需要打开 CBO。
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 设置为EditOnEnter,DataGrieViewSelectionMode 设置为CellSelect。
最后的两行来自 SO Question,“DataGridViewComboBoxColumn - Have to click cell twice to display combo box”
我不知道还能尝试什么...
【问题讨论】:
-
我看不懂
if的说法,尤其是第二部分有感叹号。我认为当列 isDataGridViewComboBoxCell类型时应该执行以下代码块。 -
@TomášPaul,
if语句只是阻止代码在单击的单元格中已存在 CBO 时执行以下代码 - 我仍然希望 CBO 在填充后在后续单击时打开,我只是不想/不需要在用户每次点击它时填充它。
标签: c# winforms datagridview datagridviewcomboboxcell