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();
}
}
}