Hide columns in a DataGridView with a list <> as a DataSource?

I have List<>a class X.

XIt has 3 columns: a, band c.

Now I bind the list to DataGridView:

dataGrid.DataSource = list;

How to show the columns of a and cin GridView, so hide the column b?

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

Any solution here?

+5
source share
5 answers

I assume your class is as follows:

private class MyClass {
  [DisplayName("Foo/Bar")]
  public string FooBar { get; private set; }
  [Browsable(False)]
  public decimal Baz { get; private set; }
  [DisplayName("Baz")]
  public CurrencyBaz
  {
        get { return string.Format(Baz, "C2"); }
  }
}

In the above code, gridview column names look like this

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

, ... [ (False)]

2 ......

, ...

+8

, DataGridView. , . , , DataGridView, .

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;
}
+6

:

dataGrid.AutoGenerateColumns = false;

X .

+3

, ,

AutoGenerateColumns False

dataGrid.AutoGenerateColumns = false;

RowDataBound Event

protected void dataGrid_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow || e.Row.RowType==DataControlRowType.Header)
            {

                e.Row.Cells[index of the cell to hide].Visible =false;

            }
        }
0
source

Or hide columns by name

dgvEmployees.DataSource = data
dgvEmployees.Columns("Id").Visible = False
dgvEmployees.Columns("ElementEtat").Visible = False
0
source

All Articles