Kervin Ramen
Kervin Ramen

Reputation: 2583

Datasource of Datagridview is null

I am populating a datagridview with objects like this:

        foreach (NavField field in this.Fields)
        {
            DataGridViewColumn column = new DataGridViewColumn();
            column.HeaderText = field.Caption;
            column.Name = field.FieldNo.ToString();
            column.ValueType = field.GetFieldType();
            column.CellTemplate = new DataGridViewTextBoxCell();

            grid.Columns.Add(column);
        }

        int count = 0;
        foreach (NavRecord record in this.Records)
        {
            grid.Rows.Add();
            foreach (NavItem item in record.items)
            {
                //Adding the rows
                grid.Rows[count].Cells[item.FieldNo.ToString()].Value = item.RecordValue;

            }
            count++;
        }

But the datasource of the grid stays null. Is there any other solution to populate the grid, or update the datasource?

Upvotes: 0

Views: 5463

Answers (2)

bernhof
bernhof

Reputation: 6310

The DataSource is null because you never set it.

You can simply set grid.DataSource = this.Records and skip the second foreach loop completely. This would require that you also set the DataPropertyName of each column you add to the grid.

This might not work with your custom NavRecord class without some modifications, though (can't say for certain unless you post the code for this as well).

foreach (NavField field in this.Fields)
{
    DataGridViewColumn column = new DataGridViewColumn();
    column.HeaderText = field.Caption;
    column.Name = field.FieldNo.ToString();
    column.ValueType = field.GetFieldType();
    column.CellTemplate = new DataGridViewTextBoxCell();
    // added:
    column.DataPropertyName = field.FieldNo.ToString();

    grid.Columns.Add(column);
}

grid.DataSource = this.Records;

Oh, and you might want to set grid.AutoGenerateColumns = false; otherwise each column might appear twice when using this approach.

Upvotes: 1

Denis Palnitsky
Denis Palnitsky

Reputation: 18387

Create DataTable and bind it to DataGrid .

dataGrid.DataSource = dataTable

Upvotes: 0

Related Questions