How to show only certain columns in a DataGridView with custom objects

后端 未结 8 1526
有刺的猬
有刺的猬 2020-12-29 07:18

I have a DataGridView and I need to add custom objects to it. Consider the following code:

DataGridView grid = new DataGridView();
grid.DataSource = objects         


        
相关标签:
8条回答
  • 2020-12-29 08:05

    The easiest is that you add the "System.ComponentModel.Browsable" attributes to your DataModel:

    public class TheDataModel 
    {
           [System.ComponentModel.Browsable(false)]
           public virtual int ID { get; protected set; }
           public virtual string FileName { get; set; }
           [System.ComponentModel.Browsable(false)]
           public virtual string ColumnNotShown1 { get; set; }
           [System.ComponentModel.Browsable(false)]
           public virtual string ColumnNotShown2  { get; set; }
    }
    
    0 讨论(0)
  • 2020-12-29 08:09

    This is my code from an old project. It can work for your case.

    OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM uyeler", baglanti);
    
    da.Fill(dbDataSet1, "uyeler");
    
    //Set AutoGenerateColumns False
    dataGridView1.AutoGenerateColumns = false;
    
    //Set Columns Count
    dataGridView1.ColumnCount = 5;
    
    //Add Columns
    dataGridView1.Columns[0].Name = "İsim"; // name
    dataGridView1.Columns[0].HeaderText = "İsim"; // header text
    dataGridView1.Columns[0].DataPropertyName = "ad"; // field name
    
    dataGridView1.Columns[1].HeaderText = "Soyisim";
    dataGridView1.Columns[1].Name = "Soyisim";
    dataGridView1.Columns[1].DataPropertyName = "soyad";
    
    dataGridView1.Columns[2].Name = "Telefon";
    dataGridView1.Columns[2].HeaderText = "Telefon";
    dataGridView1.Columns[2].DataPropertyName = "telefon";
    
    dataGridView1.Columns[3].Name = "Kayıt Tarihi";
    dataGridView1.Columns[3].HeaderText = "Kayıt Tarihi";
    dataGridView1.Columns[3].DataPropertyName = "kayit";
    
    dataGridView1.Columns[4].Name = "Bitiş Tarihi";
    dataGridView1.Columns[4].HeaderText = "Bitiş Tarihi";
    dataGridView1.Columns[4].DataPropertyName = "bitis";
    
    dataGridView1.DataSource = dbDataSet1;
    dataGridView1.DataMember = "uyeler";
    
    0 讨论(0)
提交回复
热议问题