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?
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
("Foo/Bar")
"Baz"
"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...
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;
}
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.
Or hide columns by name
dgvEmployees.DataSource = data
dgvEmployees.Columns("Id").Visible = False
dgvEmployees.Columns("ElementEtat").Visible = False
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With