There is a certain DataGridView in which columns are created manually, it is done something like this:
dataGridView.Columns.Add ("Column 1", "Heading 1");
dataGridView.Columns.Add ("Column 2", "Heading 2");
dataGridView.Columns.Add ("Column 3", "Heading 3");
How to make it so that when the data source is specified through the DataSource
property
dataGridView.DataSource = mySource;
Values from desired properties of my source went to desired columns in DataGridView . For example, let’s say my data source contains properties A , B , C and let’s say I want:
- property A was displayed in a column named “Column 3 ”
- property B in the column named “Column 2 ”
- and the property C in the column named “Column 1 ”
P.S. Now, to achieve the desired result, you have to loop through the data source and add data from it to the DataGridView as follows:
dataGridView.Rows.Add ("Value for cell 1", "Value for cell 2", "Value for cell 3 ");
Answer 1, authority 100%
You need property DataPropertyName . Let me give you a small example. Let’s have a class that describes our data:
public class MyClass
{
public MyClass (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; }
}
Add columns to DataGridView:
dataGridView.Columns.Add (new DataGridViewTextBoxColumn
{
DataPropertyName = "A",
HeaderText = "Header 1"
});
dataGridView.Columns.Add (new DataGridViewTextBoxColumn
{
DataPropertyName = "B",
HeaderText = "Header 2"
});
dataGridView.Columns.Add (new DataGridViewTextBoxColumn
{
DataPropertyName = "C",
HeaderText = "Header 3"
});
Let’s create a collection and specify it as a data source:
var data = new List & lt; MyClass & gt;
{
new MyClass ("1", "2", "3"),
new MyClass ("4", "5", "6"),
new MyClass ("7", "8", "9")
};
dataGridView.DataSource = data;
That’s all.