1

I try to get the names of SQL databases in the server in this code I listed all sql instances in my computer in a combobox named sever using sqldatasource enumerator now I am trying to get the names of all sql databases names in the another combobox when I select a specific sql instance from server combobox but it doenot work

    private void Connect_Load(object sender, EventArgs e)
    {
        sqlservertable = sqlenumeratotr.GetDataSources();

         server.DataSource = sqlservertable;

         server.DisplayMember = sqlservertable.Columns["servername"].ToString();
         server.ValueMember = sqlservertable.Columns["servername"].ToString();


    }

    private void server_SelectedIndexChanged(object sender, EventArgs e)
    {
        servername = server.SelectedValue.ToString();
        constring = "server=servername;Integrated Security = sspi";
        SqlConnection con = new SqlConnection(constring);

        con.Open();
        dbltables = con.GetSchema("Databases");



        con.Close();
        databases.DataSource = dbltables;
        databases.DisplayMember = dbltables.Columns["database_name"].ToString();
    }

2 Answers 2

3

If I understand the question correctly, I think that Heather's answer sufficiently addresses the question, I'll expand on it a bit.

You'll need to run the query that Heather mentioned, and then bind the results to the other ComboBox.

private void server_SelectedIndexChanged(object sender, EventArgs e)
{
    string serverName = server.SelectedValue.ToString();
    string connString = string.Format("server={0};Integrated Security = sspi", serverName);
    using (var con = new SqlConnection(connString))
    {
        using (var da = new SqlDataAdapter("SELECT Name FROM master.sys.databases", con))
        {
            var ds = new DataSet();
            da.Fill(ds);
            databases.DataSource = ds.Tables[0].Rows.Select(x => x["Name"].ToString());
            //...
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

2
select name from master.sys.databases

2 Comments

I believe that is the sql statement you need to execute.
the problem is that I want to get all databases in combobox when i select the instance from another combobox

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.