[Solved] SQL db and Combobox [closed]


So here we go. I will help you with such task.
First get list of databases. Then get list of tables (parameter is Connection string, where you should add the name of the database you have choosen in your combobox.

public List<string> GetDatabaseList()
{
    List<string> list = new List<string>();
    string conString = "Data Source=yourDataSource; Integrated Security=True;"; //without database declaration

    using (SqlConnection con = new SqlConnection(conString))
    {
        con.Open();

        using (SqlCommand cmd = new SqlCommand("SELECT name from sys.databases", con))
        {
            using (IDataReader dr = cmd.ExecuteReader())
            {
                while (dr.Read())
                {
                    list.Add(dr[0].ToString());
                }
            }
        }
    }
    return list;    
}

public List<string> GetTables(string database)
{
    string connectionString="Data Source=yourDataSource;Initial Catalog="+database+"; Integrated Security=True;";
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        connection.Open();
        DataTable schema = connection.GetSchema("Tables");
        List<string> TableNames = new List<string>();
        foreach (DataRow row in schema.Rows)
        {
            TableNames.Add(row[2].ToString());
        }
        return TableNames;
}

For example in your constructor of WPF window, you should set ItemsSource to your combobox of databases. Like this:

public MainWindow()
{
    InitializeComponent();
    combo_database.ItemsSource=GetDatabaseList();
}

Now create some event when your change selected index in your combobox. And set ItemsSource in your other combobox where your tables should be.

private void combo_database_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
      string db = combo_database.SelectedValue.ToString();
      var a=GetTables(db);
      combo_tables.ItemsSource=a;                      
}

3

solved SQL db and Combobox [closed]