How do I set columnNames for a dataGridView bound to a List<T>?

11,651

Solution 1

This works..

using System.ComponentModel;

List<equip> EquipList = new List<equip>();

DataGridView.Datasource = EquipList;

below:the first two properties in the class will be displayed with with their new names, the third property will not display as per the Browsable attribute.

public class equip
  {
   [DisplayName("Equipment ID")]
   public int EquipID {get;set;}

   [DisplayName("Equipment Name")]
   public string EquipName {get;set;}

   [Browsable(false)]
   public int recordId {get; private set;}
  }

Solution 2

You can try this

DataGridViewTextBoxColumn dt = new DataGridViewTextBoxColumn();
dt.DataPropertyName = "EquipName"; //Property to bind.
dt.HeaderText = "Name";
dataGridView1.Columns.Add(dt);

You can achieve this easily with Designer.

Share:
11,651
Brad
Author by

Brad

Updated on June 14, 2022

Comments

  • Brad
    Brad almost 2 years

    As shown below I have created a List of equip.I would like to have the column names more descriptive - is there an attribute that I can use in the equip.properties?

    DataGridView.Datasource = EquipList;
    
    List<equip> EquipList = new List<equip>();
    
    public class equip
    {
     public int EquipID {get;set;}
     public string EquipName {get;set;}
    }
    

    Okay, maybe I didn't explain myself properly...I am hoping that that there is an attribute that could be applied like....

    [Alis("name I would like to see in the gridview")]
    public int EquipID {get;set;}
    

    if not I'll just stick with the old tired ways

    Later on that same morning....

    I got it!

     using System.ComponentModel;
    
    [DisplayName("the nice name")]
     public int EquipID {get;set;}
    
  • Brad
    Brad about 13 years
    thats just so long and laborious
  • Bitterblue
    Bitterblue over 10 years
    @Brad This is the better answer anyways. You can add columns with 1 simple line: dataGridView1.Columns.Add("", "EquipID"); and dataGridView1.Columns.Add("", "EquipName");