C# Compare how List vs ObservableCollection behave when assigned to a DataGrid.ItemSource.

แชร์
ฝัง
  • เผยแพร่เมื่อ 14 พ.ค. 2023
  • Are you a C# programmer looking to level up your skills in data binding and user interface responsiveness? If so, you've come to the right place! In this video, we delve into the fascinating world of data binding by examining the differences between using a List and an ObservableCollection as the ItemsSource for a DataGrid control. Strap in and prepare for an eye-opening journey that will enhance your understanding of how your UI interacts with your data.
    In our code example, we have a captivating project hosted on GitHub called "CS_List_vs_ObservableCollection." By following along with the code, you'll gain hands-on experience and be able to visualize the nuances between these two data structures. So, let's dive right in!
    At the heart of the discussion lies the concept of user interface responsiveness. When you assign a List as the ItemsSource for a DataGrid, any changes made to the list won't automatically reflect in the UI. However, by utilizing an ObservableCollection, the UI will be updated dynamically as items are added or removed from the collection. This is achieved through the implementation of the INotifyCollectionChanged interface, which makes the magic happen!
    Within the MainWindow class, we explore the benefits and drawbacks of using these two different data structures. Our sample project features a collection of People objects, representing customers. By initializing an ObservableCollection*People* named AllCustomers, we ensure that any modifications made to the collection will instantly propagate to the UI.
    To illustrate this, we start by populating the collection with an initial People object. Using the Add method provided by ObservableCollection, we seamlessly incorporate the new record into the UI. Witness the power of data binding in action as the DataGrid control automatically updates to display the new entry.
    Continuing our journey, we explore scenarios where we need to save or update customer information. As you interact with the UI, observe the smooth synchronization between the ObservableCollection and the DataGrid. Whether you're adding a new record or modifying an existing one, the UI responds promptly, thanks to the underlying change notification events provided by the ObservableCollection class.
    Moreover, we demonstrate how to leverage LINQ queries to retrieve and update specific customer records within the collection. By referencing the ObservableCollection directly, you can seamlessly manipulate objects and witness the changes reflect in real time on the UI.
    But what about deletion? Fear not! We also delve into the fascinating aspect of removing items from the collection. Learn how the CollectionChanged event raises notifications when an item is removed, enabling you to update the UI or other bound objects with ease.
    Throughout the video, we emphasize the importance of using ObservableCollection when your UI requires immediate updates based on underlying data modifications. By incorporating this powerful data structure into your C# projects, you can create fluid and interactive user experiences.
    So, if you're a C# programmer seeking to harness the full potential of data binding and improve the responsiveness of your user interfaces, this video is a must-watch! By exploring the code and examples in the "CS_List_vs_ObservableCollection" project, you'll gain a deeper understanding of the inner workings of the DataGrid control and the impact of using List vs. ObservableCollection.
    ‪@SoftwareNuggets‬ #softwarenuggets

ความคิดเห็น • 14

  • @Mabh838
    @Mabh838 หลายเดือนก่อน

    Thank you for video with simple examples

    • @SoftwareNuggets
      @SoftwareNuggets  หลายเดือนก่อน

      Thanks, I also have 3 playlist full of videos about PostgreSQL. All simple to follow so you can build skills.

  • @DoctorMGL
    @DoctorMGL 2 หลายเดือนก่อน

    automatic updates from the ObservableCollection comes with a big cost when there is too much data loading on your datagrid ,
    specially that it heavily relay on Events that watch for changes all the times VS manual updates that can keep your memory free from pressure till you detect something happen "using triggers " then pushing the updating manually .
    this way you save a big performance and enhance the speed of your UI .
    and remember we often think our model is working perfect because we are testing on small data amount with less pressure .
    but in production your application users will have millions of data stacking year after year .

    • @SoftwareNuggets
      @SoftwareNuggets  2 หลายเดือนก่อน

      Hey @DoctorMGL, I agree with you 100%. Great comment. I've also learned over the years that Observable Collections offer convenience for handling dynamic data, its reliance on events can indeed be a performance bottleneck with large datasets.

  • @saulocpp
    @saulocpp 4 หลายเดือนก่อน

    Isn't it possible to change/update the information on the DataGrid itself? Aren't the rows editable?

    • @SoftwareNuggets
      @SoftwareNuggets  4 หลายเดือนก่อน +1

      Hey @saulocpp, for sure.
      dataGridView1.ReadOnly = false;
      dataGridView1.CellDoubleClick += DataGridView1_CellDoubleClick;
      dataGridView1.CellEndEdit += DataGridView1_CellEndEdit;
      private void DataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
      {
      if (e.RowIndex >= 0 && e.ColumnIndex >= 0)
      {
      dataGridView1.BeginEdit(true);
      }
      }
      private void DataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
      {
      // Update the underlying data source
      // For example, if you're using a DataTable as the DataSource
      // you would update the corresponding DataRow here
      }

    • @saulocpp
      @saulocpp 4 หลายเดือนก่อน

      @@SoftwareNuggets I will definitely try your suggestions and adapt to WPF DataGrid accordingly... after I finish watching one more of your tutorials. 😅

    • @SoftwareNuggets
      @SoftwareNuggets  4 หลายเดือนก่อน

      I hope these videos help. Thanks for the feedback.

  • @GordonWaHo
    @GordonWaHo 6 หลายเดือนก่อน

    So how could I solve this problem at 5:10? If i wanna refresh it , i must create a new list or observablecollection to copy it. Or i find a method form other video , he just let the Class Implement the Attributes INotifyPropertyChanged interface and let every attribute's set method include it.

    • @SoftwareNuggets
      @SoftwareNuggets  6 หลายเดือนก่อน

      Are you asking, how to update the Grid when the AllCustomers object was updated? I normally clear out the grid (GridCustomer.ItemsSource = null;) then i re-apply the object to the list (GridCustomer.ItemsSource = AllCustomers.)

    • @GordonWaHo
      @GordonWaHo 6 หลายเดือนก่อน

      @@SoftwareNuggets yes!that's really my question. I am the c# beginner. I use the mvvm structure in my project. Can i re binding the source (the method u
      told me )in my viewmodel class? And i
      really thanks for you answering me !

    • @SoftwareNuggets
      @SoftwareNuggets  6 หลายเดือนก่อน

      Hey @GordonWaHo, so did you add the code I suggested, and more importantly did it solve your problem? Thanks for asking questions!

    • @GordonWaHo
      @GordonWaHo 6 หลายเดือนก่อน

      Hi @SoftwareNuggets.I've already try to fixed by method you provide, It's not work.cause i declare the attributes in my viewmodel class(not in xaml.cs), i can't clear out and re-apply(like your codes). This is my codes:
      public class ShuntPlanEditorVM : Utilities.ViewModelBase
      {
      private ObservableCollection _cars = new ObservableCollection();
      public ObservableCollection Cars
      {
      get
      {
      return _cars;
      }
      set
      {
      if (value != _cars)
      {
      _cars = value;
      if (Cars != null)
      {
      OnPropertyChanged(); //INotifyPropertyChanged interface
      }
      }
      }
      }
      }
      And this is the situation: _cars.Remove(selectedCar); // UI updated
      _cars.Add(selectedCar); // UI updated
      _cars[selectindex].CarNo = other.CarNo; // Not updated
      _cars = new ObservableCollection(Cars); // UI updated
      The last line of code needs to allocate new memory. I don't think it's a good idea. Cause i need UI keep refreshing my car status data. ....emmmm so ,keep allocating memory will let my program borken right?

    • @SoftwareNuggets
      @SoftwareNuggets  6 หลายเดือนก่อน

      Let's expose Your Datagrid;
      // Assuming MyDataGrid is defined in XAML with the x:Name="MyDataGrid"
      public IEnumerable MyDataGridItemsSource
      {
      get { return MyDataGrid.ItemsSource as IEnumerable; }
      set { MyDataGrid.ItemsSource = value; }
      }
      now from other source code; you should be able to access:
      // External code or another class
      YourPage yourPageInstance = // obtain or create an instance of YourPage
      yourPageInstance.MyDataGridItemsSource = AllCustomers; // Set the ItemsSource
      // Or retrieve the ItemsSource
      IEnumerable items = yourPageInstance.MyDataGridItemsSource;