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

你。 提交于 2019-12-12 02:09:28

问题


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

回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/39264180/how-can-you-fill-combobox-in-vb-net-with-column-name-from-microsoft-sql-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!