amiry jd
amiry jd

Reputation: 27585

Add a new row to DataGrid at runtime (WPF)

I have a DataGrid and fill it when window loaded, like this:

private void Window_Loaded(object sender, RoutedEventArgs e) {
    var list = DbService.GetStuffsFull();
    dataGrid.ItemsSource = list;
}

and when i try to add a new row at run-time by this code:

Stuff item = new Stuff();
dataGrid.Items.Add(item);

I get this error:

Operation is not valid while ItemsSource is in use. Access and modify elements with ItemsControl.ItemsSource instead.

how can I add a new row at runtime?

Upvotes: 1

Views: 3808

Answers (2)

love Computer science
love Computer science

Reputation: 1828

try doing something like this: var row = dataGrid.NewRow();

    dataGrid.Rows.Add(row);
    row["column1"] = "data1";  
    row["column2"] = "data2";
    row["column3"] = "data3";

InitializeComponent();

Upvotes: 0

Snowbear
Snowbear

Reputation: 17274

You cannot modify items in Items collection if you provided it as ItemsSource. You should either add item to your list (with INotifyCollectionChanged implemented or you should initially populated Items property via Add method.

The error description is pretty clear, isn't it?

Upvotes: 1

Related Questions