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)
cnn.open()
da.SelectCommand=cmd
da.Fill(ds,"tblStaff)
Me.dgvStaff.DataSource=ds.Tables("tblStaff")

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
        'Open_DB_Connection()
        Dim SelectQry = "SELECT * FROM TableName"
        Dim SampleSource As New DataSet
        Dim TableView As DataView
        Try
            Dim SampleCommand As New SqlCommand()
            Dim SampleDataAdapter = New SqlDataAdapter()
            SampleCommand.CommandText = SelectQry
            SampleCommand.Connection = Connection
            SampleDataAdapter.SelectCommand = SampleCommand
            SampleDataAdapter.Fill(SampleSource)
            TableView = SampleSource.Tables(0).DefaultView
        Catch ex As Exception
            'Debug.Print("Exception: ")
            Throw ex
        End Try
        'Close_DB_Connection()
        Return TableView
End Function

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!

Its Mrs. Pooja :)

in load event u can call

dgvStaff.DataSource=GetData()

Sorry to call you Mr. Thank Mrs. Pooja ...

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

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.