DataGridComboBoxColumn的设置值没有反映在UI中

本文关键字:UI 设置 DataGridComboBoxColumn | 更新日期: 2023-09-27 18:13:17

我有一个包含一个值的DataGridComboBoxColumn的数据视图。我使用字符串列表设置选项,然后循环遍历行以设置该列的初始值。我可以在循环后调试,值就在那里,因为我期望它,但在UI我的组合框仍然是空的。我是否遗漏了一些可以在UI中设置值的东西,或者我做错了什么?

    private void PrepareList() {
        var dt = new DataTable {
            Columns = {
                new DataColumn("Style Number"),
                new DataColumn("Description"),
                new DataColumn("Department"),
            }
        };
        foreach (var orderEntity in _fullList) {
            foreach (var line in orderEntity.Lines) {
                dt.Rows.Add(line.VendorItemNumber, line.Description, line.Department);
            }
        }
        var view = new DataView(dt) {Sort = "Style Number asc"};
        var distinct = view.ToTable(true, "Style Number", "Description");
        dataGrid.DataSource = distinct;
        var repo = new DepartmentRepository();
        var departments = repo.GetDepartmentList();
        var vendor = new DataGridViewComboBoxColumn {
            DataSource = departments,
            ValueType = typeof(string),
            HeaderText = @"Department",
            Name = "Department",
            DataPropertyName = "Department"
        };
        dataGrid.Columns.Add(vendor);
        foreach (DataGridViewRow row in dataGrid.Rows) {
            var dtRow = dt.AsEnumerable().FirstOrDefault(r => 
                    r["Style Number"].ToString() == row.Cells["Style Number"].Value.ToString());
            var dept = dtRow == null ? "" : departments.FirstOrDefault(
                s => s.StartsWith(dtRow["Department"].ToString()));
            row.Cells["Department"].Value = dept;
        }
        dataGrid.Refresh();
        foreach (DataGridViewColumn column in dataGrid.Columns) {
            column.SortMode = DataGridViewColumnSortMode.NotSortable;
        }
    }

DataGridComboBoxColumn的设置值没有反映在UI中

dataGrid.DataSource = distinct;

这个代码应该放在:

dataGrid.Columns.Add(vendor);

:

dataGrid.Columns.Add(vendor);
dataGrid.DataSource = null;
dataGrid.DataSource = distinct;

对我来说,它的工作完美如下:

DataGridViewComboBoxColumn column = new DataGridViewComboBoxColumn();
column.Name = "new";
column.HeaderText = "New";
column.DisplayStyle = DataGridViewComboBoxDisplayStyle.DropDownButton;
column.DisplayIndex = 2;
datagridview1.Columns.Add(column);

column.DataSource = columnDataSource;
datagridview1.DataSource = null;
datagridview1.DataSource = dataGridViewDataSource;
datagridview1.Refresh();