1
votes

I've got a class with two public properties, Name and Text. I want to bind a DataGridView to a list of these objects, so I loaded them into a BindingList<>. I only want to show the Name property in the DataGridView, but I'm getting both columns. What am I doing wrong?

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;
}
2
The code you are showing does not produce two columns.LarsTech
The code I showed produces two columns for me, although I agree with you that it shouldn't.ROBERT RICHARDSON

2 Answers

2
votes

@Robert you are setting,

dgvTagNames.DataSource = m_definitions;

for that it is showing both columns. If you want to get one column use it like this,

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;

Another solution:

 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
votes

Everyone here is making things wayyyyyyy to complicated. If you have columns you don't want displayed you could just set the Column.Visible = false after the setting the datasource.

dgvTagNames.Columns[index].Visible = false;