kalamazoowho kalamazoowho - 27 days ago 18x
C# Question

Add empty row to WPF DataGrid and edit cells afterwards

I'm new to WPF and trying to convert a program from WinForms to WPF. I've come across a hiccup trying to convert from DataGridView to DataGrid and adding rows. Any help is appreciated.

Original code:

for (int i = 0; i < noteArray.Count; i++)
int newIndex = dtgrdNotes.Rows.Add();
dtgrdNotes.Rows[newIndex].Cells[0].Value = noteArray[i].ToString();
dtgrdNotes.Rows[newIndex].Cells[1].Value = chkbx1.Checked;
dtgrdNotes.Rows[newIndex].Cells[2].Value = chkbx2.Checked;

I need that code to work in WPF and I've tried different variations of dtgrdNotes.Items and even a DataRowView but nothing has worked so far. any suggestions?

Update* XAML that goes with the controls issue for Richard:

<DataGrid Name="dtgrdNotes" Height="178" Width="739" HorizontalAlignment="Right" VerticalAlignment="Bottom" Canvas.Left="1" IsEnabled="False" >
<DataGridTextColumn x:Name="dgtxtbxNote" Width="*" Binding="{Binding note}"/>
<DataGridCheckBoxColumn x:Name="dgchbxInquire" Width="100" Binding="{Binding inquire}" />
<DataGridCheckBoxColumn x:Name="dgchbxPrint" Width="100" Binding="{Binding print}" />
<DataGridTemplateColumn x:Name="dgbtncDelete" Width="80" Header="Button">
<Button x:Name="dgbtncDeleteButton" Content="Delete" Width="50px" Height="10px" FontWeight="Bold" />


In WPF, data controls must be bound to a collection of data, usually are observable collections. You can try creating a collection with one or more empty you link data and control. The Datagrid, must be equal to the model you are using. I'll leave you an example:


<DataGrid x:Name="dtgPersons" AutoGenerateColumns="False">
        <DataGridTextColumn Header="Id" Width="1*" Binding="{Binding Id}"/>
        <DataGridTextColumn Header="Name" Width="2*" Binding="{Binding Name}"/>
        <DataGridTextColumn Header="Last Name" Width="2.5*" Binding="{Binding LastName}"/>
        <DataGridTextColumn Header="Age" Width="1*" Binding="{Binding Age}"/>


public class Person
    public int Id { get; set; }
    public string Name { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }


public MainWindow()

    ObservableCollection<Person> Persons = new ObservableCollection<Person>();

    for(int i = 0; i < 10; i++)
        Person p = new Person();
        p.Id = i;
        p.Age = i + 10;
        p.Name = "Name " + i;
        p.LastName = "LastName " + i;


    dtgPersons.ItemsSource = Persons;

And the Result:

enter image description here