DataGridView bound to BindingList shows too many columns
我有一个具有两个公共属性的类,名称和文本。我想将 DataGridView 绑定到这些对象的列表,所以我将它们加载到 BindingList<> 中。我只想在 DataGridView 中显示 Name 属性,但我得到了两列。我做错了什么?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | private void fileOpenTextBox1_FileSelected(object sender, string e) { m_definitions = new BindingList<TagSimDefinition>(TagSimDefinition.Read(e)); dgvTagNames.AutoGenerateColumns = false; dgvTagNames.Columns.Clear(); DataGridViewCell cell = new DataGridViewTextBoxCell(); DataGridViewTextBoxColumn colTagName = new DataGridViewTextBoxColumn() { CellTemplate = cell, Name ="colTagName", HeaderText ="Tag Name", DataPropertyName ="Name" }; dgvTagNames.Columns.Add(colTagName); dgvTagNames.DataSource = m_definitions; } |
@Robert 你正在设置,
1 | dgvTagNames.DataSource = m_definitions; |
因为它显示了两列。如果您想获得一列,请像这样使用它,
1 2 3 4 5 6 7 8 | m_definitions = new BindingList<TagSimDefinition>(TagSimDefinition.Read(e)); dgvTagNames.AutoGenerateColumns = false; dgvTagNames.Columns.Clear(); dgvTagNames.ColumnCount = 1; dgvTagNames.Columns[0].Name ="colTagName"; dgvTagNames.Columns[0].DataPropertyName ="colTagName"; dgvTagNames.DataSource = m_definitions; |
另一种解决方案:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | m_definitions = new BindingList<TagSimDefinition>(TagSimDefinition.Read(e)); dgvTagNames.Columns.Clear(); DataGridViewCell cell = new DataGridViewTextBoxCell(); DataGridViewTextBoxColumn colTagName = new DataGridViewTextBoxColumn() { CellTemplate = cell, Name ="colTagName", HeaderText ="Tag Name", DataPropertyName ="Name" }; dgvTagNames.Columns.Add(colTagName); dgvRegion.Rows.Clear(); int index = 0; foreach (var dparam in m_definitions) { dgvTagNames.Rows.Add(); dgvTagNames["colTagName", index].Value = dparam.<Property1>; dgvTagNames.Rows[index].Tag = dparam; index++; } |
这里的每个人都让事情变得复杂。如果您有不想显示的列,则可以在设置数据源后设置 Column.Visible = false 。
1 | dgvTagNames.Columns[index].Visible = false; |