-1

Establishing windows form application with C#

There's a DataGridView grid and a ComboBox list on Form MainForm, the DataGridView has a data-binding to a DataSource _data of type DataTable , and i set the SelectedIndexChangedEventHandler to SelectedIndexChanged Event of the ComboBox. (I use MVC pattern implementation, the _data is in the Model)

A Task is started in the handler to query database and refill DataSource after clearing it, i expected the DataGridView will automatically update the content of its DataSource to the UI, but it doesn't, it just keep showing the original data(nothing).

How can i make DataGridView receive the DataSource changed event on another thread and shows the new content? thank you for help~!!

Code of the Form:

class MainForm: Form
{
    private void Initialize()
    {
        _controller = new Controller(this);
        grid.DataSource = _controller.MyModel.Data;
    }

    private void list_SelectedIndexChanged(object sender, EventArgs e)
    {
        _controller.RefreshGridViewData(list.SelectedIndex);
    }
}

Code of the Controller:

class Controller
{
    Model _model = new Model();
    public Model MyModel { get { return _model; } }

    public void RefreshGridViewData(int id)
    {
        Task.Factory.StartNew(() =>
        {
            _model.RefreshData(id);
        }
    }
}

Code of the Model:

class Model
{
    DataTable _data = new DataTable();
    public DataTable Data { get { return _data; } }

    public void RefreshData(int id)
    {
        DataTable res = GetDataFromDB(id);

         _data.Clear();
         if (res != null)
         {                               
            _data.Load(res.CreateDataReader());
            res.Dispose();
         }
    }
}
Touchout
  • 31
  • 4
  • Try raising your events to UI thread: http://stackoverflow.com/questions/1698889/raise-events-in-net-on-the-main-ui-thread – User2012384 Feb 13 '15 at 04:22

1 Answers1

0

I believe you need to Control.Invoke() an update of DataGridView.Refresh().

HouseCat
  • 1,559
  • 20
  • 22