Click here to Skip to main content
15,884,989 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Good evening! in a project created in C# WPF , I am using datagrid to give the user an empty table that the user has to fill in but I could not add a Rows to my datagrid. I would also like to give him the opportunity to add a blank line either by clicking on a button or completing a line. Thank you in advance.
Posted
Updated 6-Mar-15 10:07am
v2

1 solution

It is not so difficult you have to create a list or observeable collection and then have to bind it with your datagrid.Then when you wanna add new row just add item in your list.
As shown bellow

In XAMP:

XML
<window x:class="WpfApplication2.MainWindow" 
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <grid>
        <datagrid autogeneratecolumns="True" height="233" horizontalalignment="Left" margin="66,21,0,0" name="dataGrid1" verticalalignment="Top" width="354"></datagrid>
        <button content="Add Row" height="27" horizontalalignment="Left" margin="66,260,0,0" name="button1" verticalalignment="Top" width="72" click="button1_Click" />
    </grid>
</window>

In code behind(C#)

C#
public partial class MainWindow : Window
{
    List<employee> lstEmployee = new List<employee>();
    public MainWindow()
    {
        InitializeComponent();

       dataGrid1.CanUserAddRows=true;

    }

    void AddItemAndBind(int id)
    {
        Employee emp = new Employee();
        emp.ID = id;
        lstEmployee.Add(emp);

        dataGrid1.ItemsSource = lstEmployee;


    }



    public class Employee
    {
        public int ID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }
        public string City { get; set; }
        public string Phone { get; set; }
    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        AddItemAndBind(lstEmployee.Count+1);
    }
}
 
Share this answer
 
v4

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900