简体   繁体   中英

Manually add rows in 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 programatically, how can I manage to do this?

Thanks

Working Solution

Programatically add rows in a WPF DataGrid

You don't add rows to a grid.

  1. Bind the Grid to a List (Observable collection)
  2. Add items to that list.

Result: new rows show up in the grid.

If you don't want to databind the datagrid (even at runtime), you can follow the advice in this SO article:

programmatically add column & rows to WPF Datagrid

Basically you create a new row (in code) and populate it with items and then assign it to your grid.

Like Henk pointed out though, it isn't a great practice. If this is a one-off situation, there may be justification for it but in general you should approach it by updating the underlying data source. Here is an example from Microsoft:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM