Manually add rows to WPF DataGrid

I have the following XAML code:

<sdk:DataGrid Margin="58,8,52,18" Name="dataGridTickets"> <sdk:DataGrid.Columns> <sdk:DataGridTextColumn x:Name="ticketNoColumn" Header="Ticket No." IsReadOnly="True" Width="SizeToHeader"/> <sdk:DataGridTextColumn x:Name="seatRowColumn" Header="Seat Row" IsReadOnly="True" Width="SizeToHeader"/> <sdk:DataGridTextColumn x:Name="seatNumberColumn" Header="Seat Number" IsReadOnly="True" Width="SizeToHeader"/> </sdk:DataGrid.Columns> </sdk:DataGrid> 

I would like to enter manual data into the grid programmatically, how can I do this?

thanks

Working solution

Programmatically add rows to DataGrid WPF

+6
source share
2 answers

You do not add rows to the grid.

  • Snap grid to list (Observable collection)
  • Add items to this list.

Result: new lines appear in the grid.

+8
source

If you don't want to bind data to a datagrid (even at run time), you can follow the recommendations in this SO article:

programmatically add column and rows in WPF Datagrid

Basically, you create a new line (in code) and fill it with elements, and then assign it to your grid.

As Henk noted, this is not a good practice. If this is a one-time situation, there may be an excuse for it, but in general you should approach it by updating the main data source. Here is an example from Microsoft:

http://social.msdn.microsoft.com/Forums/en/wpf/thread/9b96a798-e185-4d90-ba73-afc35eb91643

+6
source

Source: https://habr.com/ru/post/888162/


All Articles