error updating DataGridView data source from BackgroundWorker
I have a DataGridView that uses a DataTable for its Datasource. I also have a BackgroundWorker that updates the DataTable object. This caueses an IndexOutOfRange exception when the DataTable object is updated. If I updated the DataTable on the main UI thread, there is no exception.
How can I prevent this exception? I am only updating the DataTable, not re-assigning the Datasource.
public partial class Form1 : Form
{
DataTable myData = null;
BackgroundWorker worker = new BackgroundWorker();
public Form1()
{
InitializeComponent();
myData = new DataTable();
}
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.DataSource = myData;
}
private void button1_Click(object sender, EventArgs e)
{
worker.DoWork += new DoWorkEventHandler(PopulateData);
worker.RunWorkerAsync();
}
private void PopulateData(object sender, DoWorkEventArgs e)
{
......
//update datatable
myDataAdapter.Fill(myData); //Exception caused by this call
}
}
Edit: I can workaround this by creating a second DataTable object and updating that, then setting the Datasource DataTable = the updated DataTable in the BackgroundWorker RunWorkerCompleted event, but having to have two DataTables seems a bit silly and 开发者_Go百科a waste of resources.
Edit: The exception is thrown at
Application.Run(new Form1());
in Program.cs, i.e., not by my code.
try not to create a DataTable where you do not need it yet.
I would remove this:
myData = new DataTable();
and would create it only when I can fill it with data. in fact you don't absolutely need it as part of the Form unless you want to use it from many different places.
I would then call this one:
dataGridView1.DataSource = myData;
only when all the load has been completed by the worker thread.
I had the same problem you were having except my datagridview was bound to a list. The problem occured for me when I said for the list to clear so I could then add in the new values so the list wouldn't be incorrect. I solved it by changing the datasource to something else, did what I needed to then switched it back, however it's not the nicest of work arounds.
Regardless if it's nice or not, changing the datasource is the safest bet at the moment. However instead of creating a second datatable it would be much better to:
dataGridView1.DataSource = null;
That way you don't need to bother creating another datatable.
精彩评论