0

Edit: Changed the question.

Is there a way to add Rows to Datagridview without Freezing UI?

I tried:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim t As New Threading.Thread(AddressOf CreateRows)
    t.IsBackground = True
    t.Start()
End Sub

Private Sub CreateRows()
    If DataGridView1.InvokeRequired Then
        DataGridView1.Invoke(New MethodInvoker(AddressOf CreateRows))
    Else
        For x = 0 To 25000
            DataGridView1.Rows.Add(x)
        Next
    End If
End Sub
CruleD
  • 1,153
  • 2
  • 7
  • 15
  • 1
    Check this out: [Accessing Controls from Worker Threads](http://www.vbforums.com/showthread.php?498387-Accessing-Controls-from-Worker-Threads) – jmcilhinney Oct 21 '17 at 11:31
  • Or this: https://stackoverflow.com/a/45571728/3740093 :) – Visual Vincent Oct 21 '17 at 12:47
  • For some reason Invoke is not even required, changing cells works just fine without it. On the other hand, when I try to add rows, then invoke is required. – CruleD Oct 22 '17 at 12:16
  • The code you have now is useless. You start a background thread only to move execution _**back**_ to the UI thread. You should only invoke the part _that actually updates the UI_ (which the loop itself doesn't, only `DataGridView1.Rows.Add()`). Good things to keep in mind: **1)** _**Never**_ make a method invoke itself unless you're sure what you're doing is correct, **2)** _**Never**_ invoke a loop unless it is a really fast one (your current one **is not**). – Visual Vincent Oct 27 '17 at 22:06
  • See [the answer](https://stackoverflow.com/a/45571728/3740093) I linked to instead, and use the code under _**Making it simpler**_ (be sure to read it through my answer as well, so you understand it). That extension method of mine takes care of all the "dirty work", making invoking much less of a pain. -- Also have a look at the code under _**Example**_, it'll give you a hint of how to use my extension method. – Visual Vincent Oct 27 '17 at 22:07

0 Answers0