vb.net : Error Collecting data from JSON to a datagrid from a different form/ thread

纵然是瞬间 提交于 2020-01-07 03:56:18

问题


I want to retrive data from JSON api and do other task while it's loading. I have written successful code in a form Module

Public Sub aquiredata(mygrid As DataGridView, sql As String, tablename As String)

    Dim table As DataTable
    Dim thread1 As New Thread(
      Sub()
          Try
              Dim json As String = New System.Net.WebClient().DownloadString("http://ratnt.com/api.php/" & _
        tablename & "?query=" & Chr(34) & sql & Chr(34) & "&token=" & My.Settings.token) '
                  table = JsonConvert.DeserializeObject(Of DataTable)(json)
                  MsgBox("table done")
              Finally
                  Invoke(Sub()
                             mygrid.DataSource = table
                         End Sub)
              End Try
          End Sub
        )
        thread1.Start()
    End Sub

but while I'm calling it from another form with the datagrid of that form it shows

"An unhandled exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll

Additional information: Invoke or BeginInvoke cannot be called on a control until the window handle has been created."

(P.S. I have tried with backgroundworker but the reason I avoided that it's repetative for every form because the parsing result is only completed with the RunWorkerCompleted event.)


回答1:


I missed very simple thing which is underlying in the message...

Invoke or BeginInvoke cannot be called on a control until the window handle has been created

So just a slight change mygrid.invoke instead of invoke only is working.

Thanks



来源:https://stackoverflow.com/questions/44260386/vb-net-error-collecting-data-from-json-to-a-datagrid-from-a-different-form-th

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!