Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide Columns in a DataGridView with a List<> as DataSource?

I have a List<> of a class X.

X has 3 Columns: a, b and c.

Now I bind the List on the DataGridView:

dataGrid.DataSource = list;

How to only show Column a and c in the GridView, so hide Column b?

I will not edit the list itself, if possible, and not generate a new list, if possible.

Any solution here?

like image 382
PassionateDeveloper Avatar asked Nov 08 '11 17:11

PassionateDeveloper


4 Answers

I am assuming your class is like this:

private class MyClass
{
  [DisplayName("Foo/Bar")]
  public string FooBar { get; private set; }

  [Browsable(false)]
  public decimal Baz { get; private set; }

  [DisplayName("Baz")]
  public CurrencyBaz => string.Format(Baz, "C2");
}

In the above code the gridview column names are like this

  • column name1: ("Foo/Bar")
  • column name2: "Baz"
  • column name3: "CurrencyBaz"

if you dont want to show the column you can just add this attribute: [Browsable(false)]

In the above code column name 2 is not displayed ......

I hope it will helps you...

like image 118
Glory Raj Avatar answered Oct 29 '22 05:10

Glory Raj


Hiding the columns will work but can make the DataGridView more difficult to work with. I think you are better off not to add the columns at all. To accomplish this I like to create an interface for my object that only exposes the fields I want visible in my DataGridView then bind to the interface instead of the object.

public interface IMyBindingObject
{
    string A { get; set; }
    string C { get; set; }
}


public class MyObject : IMyBindingObject
{
    public MyObject(string a, string b, string c)
    {
        A = a;
        B = b;
        C = c;
    }
    public string A { get; set; }
    public string B { get; set; }
    public string C { get; set; }
}


private void Form1_Load(object sender, EventArgs e)
{
    List<IMyBindingObject> obj = new List<IMyBindingObject>();
    obj.Add(new MyObject("Test A", "Test B", "Test C"));
    obj.Add(new MyObject("T A", "T B", "T C"));

    dataGridView1.AutoGenerateColumns = true;
    dataGridView1.DataSource = obj;
}
like image 44
RobotMike Avatar answered Oct 29 '22 05:10

RobotMike


You will need to:

dataGrid.AutoGenerateColumns = false;

Then you will need to add a column for each of the class X's members and databind those.

like image 25
Mike Mayer Avatar answered Oct 29 '22 04:10

Mike Mayer


Or hide columns by name

dgvEmployees.DataSource = data
dgvEmployees.Columns("Id").Visible = False
dgvEmployees.Columns("ElementEtat").Visible = False
like image 33
Daniel Avatar answered Oct 29 '22 04:10

Daniel