kalamazoowho kalamazoowho - 2 months ago 47
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" >
<DataGrid.Columns>
<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">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button x:Name="dgbtncDeleteButton" Content="Delete" Width="50px" Height="10px" FontWeight="Bold" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>

Answer

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:

<DataGrid x:Name="dtgPersons" AutoGenerateColumns="False">
    <DataGrid.Columns>
        <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}"/>
    </DataGrid.Columns>
</DataGrid>

Model:

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

Code:

public MainWindow()
{
    InitializeComponent();

    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;

        Persons.Add(p);
    }

    dtgPersons.ItemsSource = Persons;
}

And the Result:

enter image description here

Comments