Sebi
Sebi

Reputation: 4522

DataGrid no means of adding rows?

In VS 2019, there seems to be no way of adding rows to a DataGrid:

<DataGrid Name="myDataGrid" Background="#50000000" Grid.Row="1" Grid.Column="1" Margin="10,10,10,10" ItemsSource="{Binding myDataGRid}" AutoGenerateColumns="False" />

myDataGrid.Rows.Add(r); // <= DataGrid does not contain a definition for 'Rows' ... 

How can I add rows/columns to a DataGrid programmatically?

The table can added by columns, but this is clunky when adding new rows (column contents have to be saved, column sizes increased by 1 and refiled with previous values).

This question does not appear to be a duplicate of this one because:

Upvotes: 0

Views: 131

Answers (3)

mm8
mm8

Reputation: 169228

In VS 2019, there seems to be no way of adding rows to a DataGrid ...

VS 2019 is an IDE and the DataGrid class is part of WPF. Anyway, try the Items property:

myDataGrid.Items.Add(r); 

But if you want to be able to edit the records in the DataGrid, you should set the ItemsSource to an ObservableCollection<T> and add items to this one instead of adding items directly to the Items property.

Upvotes: 0

sven
sven

Reputation: 183

ViewModel :

....
public ObservableCollection<Customer> Customers { get; set; }
....
    
 public void AddNewCustomer(Customer customer)
 {
   
    Customers.Add(customer);
            
 }
    

xaml file : ...

<DataGrid 
ItemsSource="{Binding Path=Customers}">

...

Upvotes: 0

Miamy
Miamy

Reputation: 2299

Instead of adding rows to DataGrid directly, you should modify its data source. DataGrid will reflect any changes you make in data source, e.g. adding a new row. As mentioned in documentation:

To bind the DataGrid to data, set the ItemsSource property to an IEnumerable implementation.

Columns property can be modified programmatically:

You can use the Columns collection to programmatically add, insert, remove, and change any columns in the control at run time. Check the IsAutoGenerated property to determine whether a column is auto generated or user defined. Auto-generated columns will be automatically added, removed, or regenerated when the ItemsSource changes.

Upvotes: 1

Related Questions