Search code examples
c#wpfdatagridappend

C# WPF Appending DataGrid


I can only ever seem to get it to add the first line but then it stops. I want to basically use it as a way to save program history. So everytime the button clicks, a new line is added. Obviously the code would add static info except the timestamp for right now.

Thanks!!

      private void test_Click(object sender, RoutedEventArgs e)
    {

        {
            InitializeComponent();

            string nowtime = DateTime.Now.ToString("MM/dd/yyyy HH:mm");

            List<User> users = new List<User>();
            users.Add(new User() { ID = "1", Query = "John Doe", Timestamp = nowtime });

            historyData.ItemsSource = users;
        }
    }

    public class User
    {
        public string ID { get; set; }
        public string Query { get; set; }
        public string Timestamp { get; set; }
    }

Solution

  • There are a few things wrong with the posted code:

    1. You're creating a new list everytime the click event is fired, and setting this new list as the ItemsSource. This is the reason why only one row is ever in the grid

    2. You're unnecessarily calling InitializeComponets in the click event. This belongs in the constructor.

    3. Use an ObservableCollection instead of List for a grid's ItemsSource. This will remove the need for constantly assigning a new List everytime a change has occured.

    The changes will look something like this:

    private readonly ObservableCollection<User> users = new ObservableCollection<User>();
    
    ....
    
    public Form1()
    {
        InitializeComponets ();
        ....
        historyData.ItemsSource = users;
    }
    
    ....
    
    private void test_Click(object sender, RoutedEventArgs e)
    {
        string nowtime = DateTime.Now.ToString("MM/dd/yyyy HH:mm");
    
        users.Add(new User() { ID = "1", Query = "John Doe", Timestamp = nowtime });
    }