yat programmer
yat programmer

Reputation: 97

get list of databases in sql server based on sql instance enumeration

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

Upvotes: 1

Views: 7235

Answers (2)

lukiffer
lukiffer

Reputation: 11313

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());
            //...
        }
    }
}

Upvotes: 3

Heather
Heather

Reputation: 2662

select name from master.sys.databases

Upvotes: 2

Related Questions