sql-servervb.netdatatablecomboboxsqlcommand

How can you fill combobox in vb.net with column name from Microsoft SQL Server


How to fill combobox in vb.net with column name from Microsoft Sql Server? I have table name called Table_Categories. I wish to fill the combobox with the column names of that table . I am also planning on adding column names in the table using vb.net as its front end . how can I do it ?

    Public Sub Categories()
    Dim Connect As New SqlConnection
    Dim Adapter As New SqlDataAdapter
    Dim DataTable As New System.Data.DataTable
    Dim Query As String
    ConnectionString = "Data Source=LUSPOC-PC;Initial Catalog=Sales_Invnetory;Integrated Security=True"
    Connect = New SqlConnection(ConnectionString)
    Connect.Open()
    Connect.ChangeDatabase("Sales_Inventory")
    Query = "select Column_name from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME='Table_Categories'"
    Adapter.SelectCommand = New SqlCommand(Query, Connect)

    Adapter.Fill(DataTable)
    Admin.items_category_combobx.DataSource = DataTable
    Admin.items_category_combobx.DisplayMember = "Column_name"
    Admin.items_category_combobx.ValueMember = "Column_name"

End Sub

Solution

  • Connect.ChangeDatabase("database-name")    
    Query = "select Column_name from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME='your-Table-name'"
        Admin.items_category_combobx.DataSource = DataTable
        Admin.items_category_combobx.DisplayMember = "Column_name"
        Admin.items_category_combobx.ValueMember = "Column_name"
    

    Change your query as above and you will get column names in your dataset. For adding column, take column name and type from user. build and execute an alter table query for adding column from it.