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

k10s72fa  于 2023-03-28  发布在  .NET
关注(0)|答案(2)|浏览(119)

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
jhdbpxl9

jhdbpxl91#

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.

9njqaruj

9njqaruj2#

Using sqlconn As New SqlConnection("your connection string")
                sqlconn.Open()
                Using SqlCommand As New SqlCommand("select Column_name from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME='Table_Categories'", sqlconn)
                    SqlCommand.CommandTimeout = 0                     
                    Using sqlAdp As New SqlDataAdapter(SqlCommand)
                        sqlAdp.Fill(dt)
                    End Using
                End Using
        End Using
        ComboBox1.DataSource = dt
        ComboBox1.DataTextField = "Column_name" 
        ComboBox1.DataValueField = "Column_name"
        ComboBox1.DataBind()

相关问题