Dear All;

I would like to suggest for a function name getDataToGrid().
Example: I have table name tblStaff(StaffID,StaffName),tblPosition(PositionID,PositionName) and DataGridView anem dgvStaff. For my purpose is, I don't want to write the same code for each forms. That's why I want a function, just call to each form. It can save time and faster. My code is

Private Sub getDataToGrid()

dim cnn as new sqlClient.SqlConnection
dim cmd as new sqlClient.SqlCommand
dim dt as new DataSet
dim da as SqlClient.SqlDataAdater

cmd=new sqlClient.SqlCommand("SELECT * FROM tblStaff",cnn)

End Sub

So, I need a function to get data from table show in GridView.

Best regard,

u can try the below code

Public Function GetData() As DataView
        Dim SelectQry = "SELECT * FROM TableName"
        Dim SampleSource As New DataSet
        Dim TableView As DataView
            Dim SampleCommand As New SqlCommand()
            Dim SampleDataAdapter = New SqlDataAdapter()
            SampleCommand.CommandText = SelectQry
            SampleCommand.Connection = Connection
            SampleDataAdapter.SelectCommand = SampleCommand
            TableView = SampleSource.Tables(0).DefaultView
        Catch ex As Exception
            'Debug.Print("Exception: ")
            Throw ex
        End Try
        Return TableView
End Function

Edited 4 Years Ago by poojavb

Hey I forgot to ask you Mr.Poojavb. How can I can this function, when form load. example i have data grid name dgvStaff. Thank!

Use a DataSource control set to retrieve data using an initial SelectCommand.
In Button_click event set a new SelectCommand as you need and Rebind the GridView to show new set of data

Edited 4 Years Ago by pritaeas: Removed self promotion link.

Hey, Mrs. Pooja.It doesn't work for getData() function, problem is. Invalid object name TableName. If I code like "SELECt * from tblStaff", it's mean I can show only one table. How to do it.

This article has been dead for over six months. Start a new discussion instead.