Darkphenom
Darkphenom

Reputation: 667

Dynamically/programmatically adding values to DataGridView

Could anyone give a snippet of sample code for manually creating columns for DataGridView? I need to create columns with custom names and also manually select what values to show in the column cells. I have the DataGridView bound to a 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?
}

This msdn sample seems to be empty.

Upvotes: 0

Views: 4938

Answers (2)

Moop
Moop

Reputation: 3611

Here is a simple example on how to do it.

Here is the class of objects you want to display in the DataGridView. The things you want to display needs to be properties:

public class Fruit
{
    public string Name { get; set; }
    public Color Color { get; set; }

    public Fruit(string name, Color color)
    {
        Name = name;
        Color = color;
    }
}

And here is the code for binding this data to the DataGridView. You need to link the name of the property to the dataGridViewColumn.DataPropertyName property.

// 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;

Upvotes: 2

Marcos Lora
Marcos Lora

Reputation: 89

You can do that:

Programatically-add-new-column-to-datagridview

The columns need "DataPropertyName" Property to bind to field name.

DataGridViewTextBoxColumn

Upvotes: 1

Related Questions