Category / Section
How to update the cell styles using background thread in WinForms GridControl?
1 min read
Update cell styles
When the grid is accessed on a thread other than the created thread, the Cross-thread operation exception will be thrown. To overcome this exception, use the grid.Invoke() method based on the InvokeRequired property.
Code Snippet
C#
BackgroundWorker backgroundWorker1 = new BackgroundWorker(); backgroundWorker1.DoWork += BackgroundWorker1_DoWork; backgroundWorker1.RunWorkerAsync(); private void BackgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { Delegate d = new UpdateControlsDelegate(UpdateGrid); //To check whether the call is from the UI thread. if(this.gridControl1.InvokeRequired) { this.gridControl1.Invoke(d); } } private void UpdateGrid() { Thread.Sleep(1000); FormatGrid(); } public void FormatGrid() { for (int i = 1; i <= 100; i++) { //Applying back color to the grid. gridControl1[i, 1].BackColor = Color.Red; } }
VB
Dim backgroundWorker1 As New BackgroundWorker() AddHandler BackgroundWorker1.DoWork, AddressOf BackgroundWorker1_DoWork BackgroundWorker1.RunWorkerAsync() Private Sub BackgroundWorker1_DoWork(sender As Object, e As DoWorkEventArgs) Dim d As System.Delegate = New UpdateControlsDelegate(AddressOf UpdateGrid) 'To check whether the call is from the UI thread. If Me.gridControl1.InvokeRequired Then Me.gridControl1.Invoke(d) End If End Sub Private Sub UpdateGrid() Thread.Sleep(1000) FormatGrid() End Sub Public Sub FormatGrid() For i As Integer = 1 To 100 'Applying Styles to the grid gridControl1(i, 1).BackColor = Color.Red Next i End Sub
Sample Link:
C#: CellStyles using BackGround thread_CS
VB: CellStyles using BackGround thread_VB