如何使用 Microsoft SQL 服务器中的列名称填充 vb.net 中的组合框

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

如何使用来自 Microsoft Sql 服务器的列名称填充 vb.net 中的组合框?我有 table 个名字叫 Table_Categories。我希望用 table 的列名填充组合框。我还计划使用 vb.net 作为前端在 table 中添加列名。我该怎么做?

    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
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"

如上更改查询,您将在数据集中获得列名。要添加列,请从用户那里获取列名和类型。构建并执行 alter table 查询以从中添加列。

          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()