ComboBox 以编程方式添加到 DataGridView 单元格中,单元格单击时未展开

ComboBox added programmatically to DataGridView cell not expanding on cell click

我在 C# WinForms 项目中有一个 DataGridView,当用户单击某些 DGV 单元格时,该单元格变为 DataGridViewComboBoxCell 并且 ComboBox 填充了一些值供用户 select。这是 DataGridView_Click 事件的表单代码:

private void dgvCategories_Click(Object sender, DataGridViewCellEventArgs e)
{
    if (e.ColumnIndex == 5 && !(dgvCategories.Rows[e.RowIndex].Cells[e.ColumnIndex].GetType().Name == "DataGridViewComboBoxCell"))
    {
        // Bind combobox to dgv and than bind new values datasource to combobox
        DataGridViewComboBoxCell cboNewValueList = new 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";
                                                //" WHERE category = '" + strCategory + "'";

        // Pass validation info query to db and return list of New Values
        db getListOfNewValues = new db();
        lsNewValuesResult = getListOfNewValues.GetNewValuesList(strQueryGetNewValuesValidationInfo, strCategory, strCompanyName);

        //Populate the combobox with the list of New Values
        foreach (string strListItem in lsNewValuesResult)
        {
            cboNewValueList.Items.Add(strListItem);
        }

        // 
        dgvCategories[e.ColumnIndex, e.RowIndex] = cboNewValueList;

    }
}

这是数据库 class 中填充 ComboBox 的代码(出于这个问题的目的,这可能没有必要包括在内,但为了完整起见,我将其包括在案例是否相关):

public List<string> GetNewValuesList(string strValidationInfoQuery, string strCategory, string strCompanyName)
{
    List<string> lsValidationInfo = new List<string>();
    List<string> lsNewValuesList = new List<string>();

    using (NpgsqlConnection conn = new NpgsqlConnection(connString))
    using (NpgsqlCommand cmd = new NpgsqlCommand(strValidationInfoQuery, conn))
    {
        cmd.Parameters.AddWithValue("category", strCategory);

        conn.Open();

        using (NpgsqlDataReader reader = cmd.ExecuteReader())
        {
            while (reader.Read())
            {
                int intReaderIndex;
                for (intReaderIndex = 0; intReaderIndex <= reader.FieldCount - 1; intReaderIndex++)
                {

                    // reader indexes 3 & 4 correspond to categories.validationfield2 and validationvalue2, which can be null
                    if (string.IsNullOrEmpty(reader[intReaderIndex].ToString()))
                    {
                        lsValidationInfo.Add("");
                    }
                    else
                    {
                        lsValidationInfo.Add(reader.GetString(intReaderIndex));
                    }
                    //Console.WriteLine("reader index " + intReaderIndex + ": " + reader.GetString(intReaderIndex));
                }
            }
        }
    }

    string strValidationDb = lsValidationInfo[0];
    string strValidationTable = lsValidationInfo[1];
    string strValidationField = lsValidationInfo[2];
    string strValidationField2 = lsValidationInfo[3];
    string strValidationValue2 = lsValidationInfo[4];

    string strQueryGetNewValues = "SELECT DISTINCT " + strValidationField +
                        " FROM " + strValidationDb + "." + strValidationTable +
                        " WHERE company_id = (SELECT id FROM company WHERE name = '" + strCompanyName + "')";

    if (!string.IsNullOrEmpty(strValidationField2) && !string.IsNullOrEmpty(strValidationValue2)) strQueryGetNewValues += " AND " + strValidationField2 + " = '" + strValidationValue2 + "'";

    strQueryGetNewValues += " ORDER BY " + strValidationField;

    using (NpgsqlConnection conn = new NpgsqlConnection(connString))
    using (NpgsqlCommand cmd = new NpgsqlCommand(strQueryGetNewValues, conn))
    {
        conn.Open();

        using (NpgsqlDataReader reader = cmd.ExecuteReader())
        {
            while (reader.Read())
            {
                int intReaderIndex;
                for (intReaderIndex = 0; intReaderIndex <= reader.FieldCount - 1; intReaderIndex++)
                {
                    // reader indexes 3 & 4 correspond to categories.validationfield2 and validationvalue2, which can be null
                    if (string.IsNullOrEmpty(reader[intReaderIndex].ToString()))
                    {
                        lsNewValuesList.Add("");
                    }
                    else
                    {
                        lsNewValuesList.Add(reader.GetString(intReaderIndex));
                    }
                    Console.WriteLine("reader index " + intReaderIndex + ": " + reader.GetString(intReaderIndex));
                }
            }
        }
    }

    return lsNewValuesList;
}

组合框正在填充,因为我可以在 _Click 方法中访问 lsNewValuesResult 中的项目。 DGV 编辑模式设置为 EditOnEnter。我试过 EditOnKeystroke,但这并没有导致组合框在鼠标单击时展开。

这是单击单元格时组合框的样子,CBO 已填充并添加到 DGV 单元格:

那是在我分别单击两个单元格之后。

[已解决]

请参阅下面我的回答。

不幸地解决了这个 revealed a new issue

您可能需要关闭 AutoGenerateColumns

此外,似乎需要单击三下才能弹出下拉菜单。

    public Form1()
    {
        InitializeComponent();
        dataGridView1.AutoGenerateColumns = false;
        dataGridView1.DataSource = GetDataSource();
        DataGridViewComboBoxColumn dgvcbc = new DataGridViewComboBoxColumn();
        dgvcbc.Items.Add("R0C0");
        dgvcbc.Items.Add("R1C0");
        dgvcbc.Items.Add("R2C0");
        dgvcbc.Items.Add("R3C0");
        dgvcbc.DataPropertyName = "Col0";
        dataGridView1.Columns.Add(dgvcbc);
    }

    DataTable GetDataSource()
    {
        var dtb = new DataTable();
        dtb.Columns.Add("Col0", typeof(string));
        dtb.Columns.Add("Col1", typeof(string));
        dtb.Columns.Add("Col2", typeof(string));
        dtb.Columns.Add("Col3", typeof(string));
        dtb.Columns.Add("Col4", typeof(string));
        dtb.Rows.Add("R0C0", "R0C1", "R0C2", "R0C3", "R0C4");
        dtb.Rows.Add("R1C0", "R1C1", "R1C2", "R1C3", "R1C4");
        dtb.Rows.Add("R2C0", "R2C1", "R2C2", "R2C3", "R2C4");
        dtb.Rows.Add("R3C0", "R3C1", "R3C2", "R3C3", "R3C4");
        return dtb;
    }

您可以考虑以下有关 DataGridView 的事实:

  • 如果将 AutoGenerateColumns 设置为 false,则需要手动将列添加到 Columns 集合。

  • 如果将 AutoGenerateColumns 设置为 true,当您将数据分配给 DataSource 时,控件会自动为数据源生成列。在这种情况下,控件会在数据源的列列表中查找每一列,如果控件的 Columns 集合中没有与数据源的列名具有相同 DataPropertyName 的列,它将向 Columns 集合添加一列。

  • DataPropertyName datagridviews 的列决定了数据源的绑定列。

  • 您通常希望将 DataGridViewXXXXColumn 添加到列集合而不是对单元格使用 DataGridViewXXXXCell

  • 如果你设置EditModeEditOnEnter,那么如果你点击下拉按钮,点击一次就够了。如果单击单元格内容,则需要单击两次。

  • 如果您希望即使单击单元格内容也可以单击它,请查看。 (注:我没用过这个是例子,有点烦人。)

  • 您可以设置DisplayStyle to Nothing,然后它会将列显示为组合框,只是在编辑模式下。

使用 DataGridViewComboBoxColumn 的基本示例

我想您要在 DataGridView 中显示具有 (Id, Name, Price, CategoryId) 的产品列表,并且 CategoryId 应该来自具有 (Id, Name) 和您要将 CategoryId 显示为 ComboBox。

实际上这是DataGridViewComboBoxColumn的一个基本和经典的例子:

private void Form1_Load(object sender, EventArgs e) {
    var categories = GetCategories();
    var products = GetProducts();
    var idColumn = new DataGridViewTextBoxColumn() {
      Name = "Id", HeaderText = "Id", DataPropertyName = "Id"
    };
    var nameColumn = new DataGridViewTextBoxColumn() {
      Name = "Name", HeaderText = "Name", DataPropertyName = "Name"
    };
    var priceColumn = new DataGridViewTextBoxColumn() {
      Name = "Price", HeaderText = "Price", DataPropertyName = "Price"
    };
    var categoryIdColumn = new DataGridViewComboBoxColumn() {
      Name = "CategoryId", HeaderText = "Category Id", DataPropertyName = "CategoryId",
      DataSource = categories, DisplayMember = "Name", ValueMember = "Id",
      DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing
    };
    dataGridView1.Columns.AddRange(idColumn, nameColumn, priceColumn, categoryIdColumn);
    dataGridView1.EditMode = DataGridViewEditMode.EditOnEnter;
    dataGridView1.AutoGenerateColumns = false;
    dataGridView1.DataSource = products;
}
public DataTable GetProducts() {
    var products = new DataTable();
    products.Columns.Add("Id", typeof(int));
    products.Columns.Add("Name", typeof(string));
    products.Columns.Add("Price", typeof(int));
    products.Columns.Add("CategoryId", typeof(int));
    products.Rows.Add(1, "Product 1", 100, 1);
    products.Rows.Add(2, "Product 2", 200, 2);
    return products;
}
public DataTable GetCategories() {
    var categories = new DataTable();
    categories.Columns.Add("Id", typeof(int));
    categories.Columns.Add("Name", typeof(string));
    categories.Rows.Add(1, "Category 1");
    categories.Rows.Add(2, "Category 2");
    return categories;
}

了解更多

要了解有关 DataGridView 的更多信息,请查看 DataGridView Control (Windows Forms)。它包含一些文档和有用的 How To 文章的链接,包括:

您是否遇到了由于某种原因未显示的错误?

如果我使用你的代码,DataGridViewComboBoxCell 似乎填充了值,但我得到 DataGridViewComboBoxCell value is not valid 运行时错误。

这个测试代码对我来说工作正常:

private void dgvCategories_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    DataGridViewComboBoxCell cboNewValueList = new DataGridViewComboBoxCell();

    List<string> lsNewValuesResult = new List<string>();
    lsNewValuesResult.Add("Value1");
    lsNewValuesResult.Add("Value2");
    lsNewValuesResult.Add("Value3");

    foreach (string strListItem in lsNewValuesResult)
    {
        cboNewValueList.Items.Add(strListItem);
    }

    dgvCategories[e.ColumnIndex, e.RowIndex] = cboNewValueList;

    // Added setting of initial value
    cboNewValueList.Value = cboNewValueList.Items[0];   
}

因此,也许在将 DataGridViewComboBoxCell 添加到 DataGridView 之后尝试设置其初始值。

如果我正确识别你的问题,我会在我的测试应用程序中添加一个 DataGridView whit 6 列,EditMode = EditOnEnter (其他的需要点击三次打开下拉菜单,据我所知)并处理CellStateChanged事件。

private void dgvCategories_CellStateChanged(object sender, DataGridViewCellStateChangedEventArgs e)
{
    if (e.StateChanged == DataGridViewElementStates.Selected)
    {
        DataGridViewCell cell = e.Cell;
        int columnIndex = cell.ColumnIndex;
        int rowIndex = cell.RowIndex;
        //---IF CONDITIONS--
        //columnIndex == 5
        //          Only cells in Columns[5]
        //cell.Selected
        //          Because this event raised two time, first for last selected cell and once again
        //          for currently selected cell and we need only currently selected cell.
        //cell.EditType.Name != "DataGridViewComboBoxEditingControl"
        //          If this cell "CellStateChanged" raised for second time, only other cell types allowed
        //          to edit, otherwise the current cell lost last selected item.
        if (columnIndex == 5 && cell.Selected && cell.EditType.Name != "DataGridViewComboBoxEditingControl")
        {
            DataGridViewComboBoxCell cboNewValueList = new DataGridViewComboBoxCell();

            //Add items to DataGridViewComboBoxCell for test, replace it with yours.
            for (int i = 0; i < 10; i++)
                cboNewValueList.Items.Add($"Item {i}");

            dgvCategories[columnIndex, rowIndex] = cboNewValueList;
        }
    }
}

NOTE: user must click two time in a cell to open drop down menu.

编辑一个: 正如 Reza Aghaei 建议在单元格中单击:

private void dgvCategories_CellClick(object sender, DataGridViewCellEventArgs e)
{
    DataGridViewComboBoxEditingControl editingControl = dgvCategories.EditingControl as DataGridViewComboBoxEditingControl;
    if (editingControl != null)
        editingControl.DroppedDown = true;
}

我要公开承认我傻了:

出于该项目所需的设计和功能原因,我手动设置 DGV 列的宽度和名称,并且我还需要第 2 到第 4 列 ReadOnly = true。好吧,我无意中设置了第5列-这个问题即将ReadOnly = true的列。

感谢大家的回答。这只是提醒我们,如此简单的事情可能会导致一个看似大的问题,而且很容易被忽视!