有人可以提供一段示例代码来手动创建DataGridView的列吗?我需要创建具有自定义名称的列,并手动选择要在列单元格中显示的值。我将DataGridView绑定到Collection<>
private void initialiseDataGridView(Part part, string batchNumber){
dataCollection = new DataCollection(part.name, batchNumber);
dataCollectionSource = new BindingSource(dataCollection, null);
serialConDataGrid.DataSource = dataCollectionSource;
serialConDataGrid.AutoGenerateColumns = false;
// Add columns
DataGridViewCheckBoxColumn selectedCol = new DataGridViewCheckBoxColumn(false);
selectedCol.HeaderText = "Selected";
DataGridViewColumn runNumberCol = new DataGridViewColumn();
runNumberCol.HeaderText = "Run Number";
serialConDataGrid.Columns.Clear();
serialConDataGrid.Columns.Add(selectedCol);
serialConDataGrid.Columns.Add(runNumberCol);
// How can I specify which values to populate into the column cells here?
}
答案 0 :(得分:2)
这是一个关于如何做的简单示例。
以下是您要在DataGridView
中显示的对象类。您想要显示的内容需要是属性:
public class Fruit
{
public string Name { get; set; }
public Color Color { get; set; }
public Fruit(string name, Color color)
{
Name = name;
Color = color;
}
}
以下是将此数据绑定到DataGridView
的代码。您需要将属性的名称链接到dataGridViewColumn.DataPropertyName
属性。
// The list of objects
List<Fruit> fruit = new List<Fruit>( )
{new Fruit("Apple",Color.Red),
new Fruit("Orange",Color.Orange),
new Fruit("Pear",Color.Green)};
BindingSource source = new BindingSource(fruit, null);
dataGridView1.AutoGenerateColumns = false;
DataGridViewTextBoxColumn column = new DataGridViewTextBoxColumn();
column.HeaderText = "Name Of Fruit";
column.DataPropertyName = "Name"; // Name of the property in Fruit
dataGridView1.Columns.Add(column);
DataGridViewTextBoxColumn colorColumn = new DataGridViewTextBoxColumn();
colorColumn.HeaderText = "Color";
colorColumn.DataPropertyName = "Color"; // Name of the property in Fruit
dataGridView1.Columns.Add(colorColumn);
dataGridView1.DataSource = source;
答案 1 :(得分:1)