How to refresh datagrid with code

What I hope is to let user can re-query data from database by typing SQL command in the textbox and clicking command button.

The result is that it can work only in the first query. Thatis, datagrid will not changed when new SQL command is conduct.




Gerenal Declaration

Dim rec As ADODB.Recordset
Dim con As ADODB.Connection

Private Sub Command1_Click()


On Error Resume Next
rec.CursorLocation = adUseClient

a = Text1.Text
rec.Open a, con
rec.Requery

Set DataGrid1.DataSource = rec
DataGrid1.Refresh
End Sub

Private Sub Form_Load()
Set con = New ADODB.Connection
Set rec = New ADODB.Recordset

con.Open "DSN=pubs;UID=edwardchung;PWD=;"
End Sub
tajenAsked:
Who is Participating?
 
KurvyConnect With a Mentor Commented:
before the refresh try rebinding the data

0
 
tajenAuthor Commented:
I add datagrid1.rebind before datagrid1.refresh.
But datagrid1 still can not change the context after new SQL command was run.
0
 
kthackerCommented:
Try setting datagrid1.datasource = nothing first.
0
 
tajenAuthor Commented:
I add set datagrid1.datasource=nothing in first line in command_click1()

But it still does not work
0
 
kthackerCommented:
Close the recordset before you open it.  You will have to check the state first to see if it is open before you close it.

If rec.State = adStateOpen then
   rec.close
endif

I tried this and it worked.

0
All Courses

From novice to tech pro — start learning today.