'DataGridView ScrollBars are not working after Thread
I'm setting a dataTable as data source of a datagridview. I do this on a new thread (I don't want my UI blocked while is loading data). My dilema is: the scrollbars are not working after the thread finishes. I tryed setting Scrollbars.None before load the data, and Scrollbars.Both after. Also tryed with Refresh. But only helped me to show the scrollbars, these still without working.
If I use the same code in my principal, thread it works perfectly.
so how can I do to make it work?
My code:
private void PressKey(object sender, KeyPressEventArgs e)
{
var process = new Thread(this.LoadData);
process.Start();
}
private void LoadData()
{
CheckForIllegalCrossThreadCalls = false;
this.dgv.ScrollBars = ScrollBars.None;
this.dgv.Columns.Clear();
this.dgv.DataSource = MyDataTable;
this.dgv.ScrollBars = ScrollBars.Both;
}
Solution 1:[1]
Ok, I finally got it. I used MethodInvoker inside of my thread. It allows me run on UI thread and update the controls:
private void LoadData()
{
CheckForIllegalCrossThreadCalls = false;
this.dgv.Columns.Clear();
this.dgv.DataSource = MyDataTable;
this.Invoke((MethodInvoker)delegate
{
dgv.ScrollBars = ScrollBars.Both; // runs on UI thread
});
}
Solution 2:[2]
I think the UI and datasource binding of DataGridView are not in the same thread. So its UI cannot aware that the datasource has been bind. Could you try that: implement the delegate for DataBindingComplete with setting the ScrollBars to Both?
For example:
private void dataGridView_DataBindingComplete(object sender,
DataGridViewBindingCompleteEventArgs e)
{
this.dgv.ScrollBars = ScrollBars.Both;
}
The document: https://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.databindingcomplete(v=vs.110).aspx
Solution 3:[3]
You need to do UI operations in UI thread to take effect.
//UI Thread
this.Invoke((MethodInvoker)delegate
{
//DataGridview Refreshment
dataGridView.Enabled = true;
dataGridView.ScrollBars = ScrollBars.Both;
});
Solution 4:[4]
As Joel added to DannSahn's answer, you must set the scrollbars properties to none, using the invoke method will set them up.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | DannSaHa |
Solution 2 | Hien Nguyen |
Solution 3 | DiRiNoiD |
Solution 4 |