Cross-thread operation not valid

前端 未结 2 1853
花落未央
花落未央 2020-12-21 15:51

I was doing the following to try out threadings but get the \'Cross-Threading\' error in the line txtBox.Text = DataGridView2.Rows.Item(iloop).Cells(3).Value, a

2条回答
  •  眼角桃花
    2020-12-21 16:23

    It's not legal to access a UI element from anything other than UI thread in .Net code. Hence when you try and use the DataGridView2 instance from a background thread it rightfully throws an exception.

    In order to read or write to a UI component you need to use Invoke or BeginInvoke method to get back on the UI thread and make the update. For example

    If TypeOf cCtrl Is TextBox Then
        Dim txtBox As TextBox
        txtBox = cCtrl
        txtBox.Invoke(AddressOf UpdateTextBox, txtBox, iloop)
    End If
    
    Private Sub UpdateTextBox(txtBox as TextBox, iloop as Integer) 
        If (txtBox.Name.Substring(9, 6)) = (DataGridView2.Rows.Item(iloop).Cells(0).Value.substring(0, 6)) Then
            txtBox.Text = DataGridView2.Rows.Item(iloop).Cells(3).Value 'This is the part that says "Cross-thread operation not valid: Control 'txt_Time_00_000' accessed from a thread other than the thread it was created on."
        End If
    End Sub
    

提交回复
热议问题