首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >您能在手动添加的DataGridView上对DataGridViewComboBox进行排序吗?

您能在手动添加的DataGridView上对DataGridViewComboBox进行排序吗?
EN

Stack Overflow用户
提问于 2016-02-14 03:33:13
回答 1查看 119关注 0票数 0

我有一个DataGridView,它是从绑定源代码的DataTable中填充的。我通过DataTable的ColumnMapping隐藏一列

代码语言:javascript
运行
复制
dataTable.Columns[“ZoneId“].ColumnMapping = MappingType.Hidden;

我已经将DataGridView的DataBindingComplete事件绑定到一个方法,该方法遍历行,查看DataBound ZoneId列,然后为该行设置ComboBox以匹配ZoneId。

代码语言:javascript
运行
复制
for (int i = 0; i < dataGridView.Rows.Count - 1; i++) {  //Count-1 to ignore the editing row
  // This is the DataGridView row, a subset of the backing data plus the combo and button cells
  DataGridViewRow row = dataGridView.Rows[i];
  // This is the full backing data for the row
  DataRowView dataRow = (DataRowView)row.DataBoundItem;
  if (dataRow != null) {
    // Find cell with comboBox by name 
    DataGridViewComboBoxCell cell = DataGridViewComboBoxCell)row.Cells["ZoneIdComboBox"];
    if (cell != null) {
      Id = (string)dataRow["ZoneId"];
      cell.Value = Id;
    }
  }
}

ComboBox的值等于表中存储的隐藏列值(ID)。文本部分是对该值的人类可读的描述。它们是由数据库中的一个单独的表定义的。另外,这两个表有一个关系,所以我的主表中的ZoneId必须在我的ComboBox表中映射一个Id。

我可以单击任何定期绑定列的标题并对表进行排序。我希望能够单击ComboBox列并对文本条目进行排序。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-02-15 22:40:19

真正的解决方案是设置AutoGenerateColumns = false。然后手动创建所有列。在最初加载DataGridView时,我会这样做。从那以后我就不用再做了。

代码语言:javascript
运行
复制
private DataGridViewComboBoxColumn MakeDataGridViewComboBoxColumn(string fieldName, string headerText, DataGridViewColumnSortMode sortMode, bool readOnly)
{
  DataGridViewComboBoxColumn result = new DataGridViewComboBoxColumn();
  result.Name = fieldName;
  result.DataPropertyName = fieldName;
  result.HeaderText = headerText;
  result.SortMode = sortMode;
  result.ReadOnly = readOnly;
  return result;
}

之后,我使用单独的ComboBox列填充列表或数据表。

代码语言:javascript
运行
复制
private void QueueBindZoneColumn()
{
  // The available ZoneId list may have been edited, so get a fresh copy
  DataGridViewComboBoxColumn c = (DataGridViewComboBoxColumn)dgv1.Columns["ZoneId"];
  if (c != null) {
    c.ValueType = typeof(string);
    List<Data.Zone> ZoneList;
    if (Data.LoadZoneId.Load(txtConnectionString.Text, out ZoneList)) {
      c.DataSource = ZoneList;
      c.DisplayMember = "ZoneDescription";    //List class member name to display as descriptions
      c.ValueMember = Data.FieldNameHandling.Id;  //List class member name to use as the stored value
    }
  }
}

当分配DataGridView BindingSource时,会设置ComboBox值,因为表的fieldName与ComboBox的DataPropertyName匹配。

最重要的是,这意味着我不必像以前那样手动处理从ComboBox更改到备份存储数据的数据分配。

它还处理数据的变化,现在我需要更长的时间来验证ComboBoxes。

加载数据后,我可以根据ComboBox中的值对行进行排序。我可能会重写排序方法来对文本信息进行排序。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35388061

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档