0

i have a combobox on the form and a datagrid viewer .no i want to display the table which selected on combo box...i am newer to vb.net so plz explain me detailed manner with code..

very very very much thanks for any help...

2
Contributors
1
Reply
2
Views
7 Years
Discussion Span
Last Post by Oxiegen
0

Ok. From the beginning.
From populating your combobox, selecting table and reading into DataGridView.
This assumes that the database type is an MS SQL server.

Imports System.Data.SqlClient

'''Read table names from database
Private Sub ReadTables()
   Dim con As New SqlConnection("<connectionstring>")
   Dim com As SqlCommand = Nothing
   Dim dr As SqlDataReader = Nothing
   Dim schemaTable As DataTable

   Try
      combobox1.Items.Clear()

      con.Open()

      'Get table and view names
      com = New SqlCommand("SELECT DISTINCT name FROM sysobjects WHERE xtype='U'", con)
      dr = com.ExecuteReader(CommandBehavior.CloseConnection)
      If dr.HasRows Then
         While dr.Read
            combobox1.Items.Add(dr.item("name"))
         End While
      End If
      dr.Close()
   Catch ex As Exception
      If con.State = ConnectionState.Open Then
         con.Close()
      End If
   End Try
End Sub

'''Select table from combobox
Private Sub combobox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles combobox1.SelectedIndexChanged
   If combobox.SelectedIndex > -1 Then
      ReadFromDataBase(combobox.SelectedItem)
   End If
End Sub

'''Read from database and display in DataGridView
Private Sub ReadFromDataBase(table As String)
   Dim con As New SqlConnection("<connectionstring>")
   Dim com As SqlCommand = Nothing
   Dim da As SqlDataAdapter = Nothing

   Dim table As DataTable

   Try
      con.Open()
      com = New SqlCommand("SELECT * FROM " & table, con)
      da = New SqlDataAdapter(com)
      da.Fill(table)
      con.Close()

      datagridview.DataSource = Nothing
      datagridview.DataSource = table
   Catch ex As Exception
      If con.State = ConnectionState.Open Then
         con.Close()
      End If
   End Try
End Sub
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.