Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 381
Sandeep Bansal Avatar asked May 15 '11 21:05

Sandeep Bansal


People also ask

How to add rows in Wpf DataGrid?

WPF DataGrid (SfDataGrid) provides built-in row called AddNewRow. It allows user to add a new row to underlying collection. You can enable or disable by setting SfDataGrid. AddNewRowPosition property.

How do I create a dynamic grid in WPF?

The Grid class in WPF represents a Grid control. The following code snippet creates a Grid control, sets its width, horizontal alignment, vertical alignment, show grid lines, and background color. Grid DynamicGrid = new Grid();

What is the difference between DataGrid and DataGridView?

The DataGrid control is limited to displaying data from an external data source. The DataGridView control, however, can display unbound data stored in the control, data from a bound data source, or bound and unbound data together.

What is DataGrid WPF?

A DataGrid is a control that displays data in a customizable grid. It provides a flexible way to display a collection of data in rows and columns. The hierarchical inheritance of DataGrid class is as follows −


2 Answers

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

like image 170
IAmTimCorey Avatar answered Oct 17 '22 16:10

IAmTimCorey


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.

like image 29
Henk Holterman Avatar answered Oct 17 '22 16:10

Henk Holterman