我有一个有两个公共属性的类,名称和文本。我想将DataGridView绑定到这些对象的列表,所以我将它们加载到BindingList<>中。我只想在DataGridView中显示Name属性,但我得到了两个列。我做错了什么?
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;
}
答案 0 :(得分:2)
@Robert你正在设置,
dgvTagNames.DataSource = m_definitions;
表示它显示两列。如果你想让一个列像这样使用它,
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;
另一种解决方案:
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++;
}
答案 1 :(得分:1)
这里的每个人都在努力让事情变得复杂起来。如果您有不希望显示的列,则可以在设置数据源后设置Column.Visible = false。
dgvTagNames.Columns[index].Visible = false;