0
votes

I'm trying to populate a datagridview on a form with a list of objects with multiple properties in order to create a table.

  private void display()
  {
        DataGridViewName.AutoGenerateColumns = false;
        DataGridViewName.DataSource = Class.List;
        DataGridViewName.ClearSelection();
  }

When I have AutoGenerateColumns set to false, nothing shows up in the cells (I used designmode to input column headers), if I change AutoGenerateColumns to true, it adds a column for each parameter and the column header shows the name of the property. Any explanation why the data isn't showing with it set to false, and if not then is there a way to change the column header name from the property name to something else on the autogenerated columns?

1
If you created the columns in the designer, does each columns DataPropertyName match one of the class properties names?JohnG
That was it! The datapropertyname in design mode was blank, once I changed it to the property name it fixed it. Thanks!L P
@LP, also I will advise you to not set this property in designer, because you a creating "magic string". Suppose some days after you will rename your properties and your DataGridView go Boom. It is better to set it by code in constructor: yourColumn1.DataPropertyName = nameof(YourClass.YourProperty);vasily.sib
@vasily.sib good call, that makes sense. adjusting accordinglyL P
@vasily.sib … I have to ask from your comment… ”I will advise you to not set this property in designer, because you a creating "magic string".” … I am not sure how this property qualifies as a “magic string.” Can you elaborate why this is a “magic string.”? In addition, your next comment… ”Suppose some days after you will rename your properties and your DataGridView go Boom.” …. ??? I can only recommend you more carefully “rename your properties.”JohnG

1 Answers

0
votes

You need to use AutoGenerateColumn = false

and set DataPropertyName for each column

and then you could change the header setting HeaderText property