DataGridViewComboBoxColumn将不同的项添加到每一行。

时间:2020-03-06 14:20:51  来源:igfitidea点击:

我正在使用DataGridView构建表,用户可以在其中从每个单元格的下拉列表中选择项目。为了简化问题,可以说我有1列。我在设计器中使用DataGridViewComboBoxColumn。我试图支持让该列中的每一行都有不同的项目列表供我们选择。

这可能吗?

解决方案

是的。这可以使用DataGridViewComboBoxCell来完成。

这是将项目添加到一个单元格而不是整个列的示例方法。

private void setCellComboBoxItems(DataGridView dataGrid, int rowIndex, int colIndex, object[] itemsToAdd)
{
    DataGridViewComboBoxCell dgvcbc = (DataGridViewComboBoxCell) dataGrid.Rows[rowIndex].Cells[colIndex];
    // You might pass a boolean to determine whether to clear or not.
    dgvcbc.Items.Clear();
    foreach (object itemToAdd in itemsToAdd)
    {
        dgvcbc.Items.Add(itemToAdd);
    }
}

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
    if (e.ColumnIndex == DataGridViewComboBoxColumnNumber)
    {
        setCellComboBoxItems(myDataGridView, e.RowIndex, e.ColumnIndex, someObj);
    }
}