Search code examples
c#datagridviewbackgroundworker

Correctly setting visibilities of entries in a DataGridView from a BackGroundWorker


I have a DataGridView, which has some DataSource. I need to filter the items in the DataGridView, based on some criteria the user specifies.

The problem is that the data is on a very slow database. For many of the items I can filter on information which is stored on the items themselves (which is quick), but sometimes I need to query the database to figure out wether or not a row should be visible.

Hence, I use a BackGroundWorker in the following way:

  1. I make a copy (using CopyTo) of the rows in the DataGridView and pass this to the RunWorkerAsync method
  2. In the DoWork method, I check each of the DataGridViewRow elements in the array. Sometimes I can simply look up the information in the row(E.g. read column 2 on the DataGridViewRow), sometimes I need to query the database.
  3. Each time i know wether or not a row should be visible, I send a tuple consisting of a row number(Simply the position in the passed array of DataGridViewRow elements) and a boolean indicating the visibility to the ReportProgress method, which sets the visibility on the DataGridView.

The reason for copying (using CopyTo) is to avoid accessing the DataGridViews RowCollection from another thread.

All this works fine, but I am really wondering if this is a really bad way to do it.

  • Is it a really bad practice to operate on a RowCollection like this?
  • If it is okay, is it necessary to use CopyTo? The reason I do it is because lists are passed by reference, and I wanted to avoid accessing the UI from a seperate thread.

Thanks for your time.


Solution

  • I think your GUI is too tight to the database for a background worker.

    In general I prefer to use BindingList<T> to bind the grid to, and manipulate the list instead of going through database. But if I have a fairly big amount of data to retrieve from database then I might enable the "virtual mode" of the datagridview, and again make use of the BindingList<T>.

    Hope this helps.

    EDIT1: Of course you can use filtering directly over your DataTables... but then maybe you should not involve the background worker.

    EDIT2: I see BindingList<T> as a chance to bind the view to a model, and not to the data layer directly, which in general is better because separates data layer of presentation layer. Even more, you could create a view-model from the model to bind the grid to (MVVM pattern). But really depends on your project.