8

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

Sandeep Bansal
  • 6,280
  • 17
  • 84
  • 126

2 Answers2

8

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.

H H
  • 263,252
  • 30
  • 330
  • 514
  • 7
    Why not? I know it isn't the normal use, but it can be done. There can be instances where adding items to a list isn't a preferred method of operating. – IAmTimCorey May 15 '11 at 21:48
  • 8
    @Biggs: those instances are called spaghetti-road. Add an intermediate list if you have to. A control is not a data-structure. – H H May 15 '11 at 21:50
  • @Henk Holterman - true, I guess I was just trying to directly address the OP's question and it is technically possible. You are correct though that you should be editing the underlying data structure rather than the UI control. – IAmTimCorey May 15 '11 at 21:55
  • Thanks for that, I did think about a list and it would be a choice, how would the List be coded to be for 3 columns? – Sandeep Bansal May 15 '11 at 22:03
  • You'll need a class with 3 properties, and a ObservableCollection. Bind it to the Grid.ItemSource. – H H May 15 '11 at 22:07
8

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

Community
  • 1
  • 1
IAmTimCorey
  • 16,412
  • 5
  • 39
  • 75