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

后端 未结 8 1649
有刺的猬
有刺的猬 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:03

    You can use databindings with AutoGenerateColumns = false and using DataPropertyName like this

    grid.Columns["Column_name_1"].DataPropertyName = "public_property_1";
    grid.Columns["Column_name_2"].DataPropertyName = "public_property_2";
    

    This way only bound columns will be shown in the datagridview, and you can create the columns in the editor if you want. Public properties can be any public attribute within your object.

    If you are editing your data from the datagridview, then you should use NotifyPropertyChanged in the set methods. Se my question/answer here where I explain this all the way down.

提交回复
热议问题