在数据网格视图 C# 中放置列表框/下拉菜单

本文关键字:列表 下拉菜单 数据网 数据 网格 视图 | 更新日期: 2023-09-27 18:37:15

我在数据网格视图中有一个数据表。我想将列表框/下拉菜单放在特定的列和行中。我已经试过了,但它不起作用——

var column = new DataGridViewComboBoxColumn();
            RunTimeCreatedDataGridView[1, 1].Value = RunTimeCreatedDataGridView.Columns.Add(column); 

以下是我填充表格的方式——

public DataTable createGridForForm(int rows, int columns)
{              
    // Create the output table.
    DataTable table = new DataTable();
    for (int i = 1; i <= columns; i++)
    {
        table.Columns.Add("column " + i.ToString());
    }
    for (int i = 1; i < rows; i++)
    {
        DataRow dr = table.NewRow();
        // populate data row with values here
        ListBox test = new ListBox();
        myTabPage.Controls.Add(test);
        table.Rows.Add(dr);
    }
    return table;
}

以下是我创建数据网格视图的方法。

private void createGridInForm(int rows, int columns)
{
    DataGridView RunTimeCreatedDataGridView = new DataGridView();
    RunTimeCreatedDataGridView.DataSource = createGridForForm(rows, columns);
    //DataGridViewColumn ID_Column = RunTimeCreatedDataGridView.Columns[0];
    //ID_Column.Width = 200;
    int positionForTable = getLocationForTable();
    RunTimeCreatedDataGridView.BackgroundColor = Color.WhiteSmoke;
    RunTimeCreatedDataGridView.Size = new Size(995, 200);
    RunTimeCreatedDataGridView.Location = new Point(5, positionForTable);
    myTabPage.Controls.Add(RunTimeCreatedDataGridView);                   
}

在数据网格视图 C# 中放置列表框/下拉菜单

你的第一个

代码块走上了正轨......问题是您正在尝试向单元格引用添加列。如果要添加所有行都有下拉列表的列,请完全按照您正在执行的操作进行操作,但只需添加该列而不是指定单元格值,如下所示:

var column = new DataGridViewComboBoxColumn();
RunTimeCreatedDataGridView.Columns.Add(column);

然后,像通常对组合框一样指定数据源。

或者,如果您希望特定单元格具有不同的组合框,

或者只有列中的单个单元格具有一个组合框,则可以创建一个单独的组合框,如下所示或此处。

编辑:若要将组合框添加到 DataGridView 中的特定单元格,请执行如下操作:

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            DataGridView dgv = new DataGridView();
            // add some columns and rows
            for (int i = 0; i < 10; i++)
            {
                DataGridViewCell c = new DataGridViewHeaderCell();
                dgv.Columns.Add("Column" + i, Convert.ToString(i));
            }
            for (int i = 0; i < 10; i++)
            {
                dgv.Rows.Add(new DataGridViewRow());
            }
            //create a new DataGridViewComboBoxCell and give it a datasource
            var DGVComboBox = new DataGridViewComboBoxCell();
            DGVComboBox.DataSource = new List<string> {"one", "two", "three"};
            DGVComboBox.Value = "one"; // set default value of the combobox
            // add it to cell[4,4] of the DataGridView
            dgv[4, 4] = DGVComboBox;
            // add the DataGridView to the form
            this.Controls.Add(dgv);
        }
    }