首页 > 解决方案 > Get tables names of a specific database selected by user from combobox

问题描述

I am working in visual studio to get the database names in SQL server and in obtaining those I am successful.But now I want to fill a combobox with the tables names of a database that is selected by user from another combobox. Here is what I have tried so far when I run the application the combobox for table names is filled for the Database that I have mentioned in the query.But it should depend on the user that if he selects any database from combobox then the table names for that database should be populated in table names combobox. So the user must not mention explicitly the name of database in query.

Basically it should pick the name of selected database from combobox and populate another combobox with respected table names.

using (SqlCommand com = new SqlCommand("SELECT TABLE_NAME FROM 
RegistrationFrom.INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'", 
con))
{
                using (SqlDataReader reader = com.ExecuteReader())
                {
                    //comboBox1.Items.Clear();
                    while (reader.Read())
                    {
                        comboBox1.Items.Add((string)reader["TABLE_NAME"]);
                    }
                }
            }

标签: c#sql-serverwinformsvisual-studio

解决方案


您需要将RegistrationFrom替换为您的第一个组合框的值。

System.Text.StringBuilder myQuery = new System.Text.StringBuilder();
myQuery.AppendFormat("SELECT TABLE_NAME FROM {0}.INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'", valueOfCombobox);

using (SqlCommand com = new SqlCommand(myQuery.ToString(), con))
{
    using (SqlDataReader reader = com.ExecuteReader())
    {
        //comboBox1.Items.Clear();
        while (reader.Read())
        {
            comboBox1.Items.Add((string)reader["TABLE_NAME"]);
        }
    }
}

推荐阅读