14

I have created a desktop application. On application launch I want to display the list of all available SQL Server instances on the local PC, and allow to choose a SQL Server name to connect with.

Is there anyway to get the list of all SQL Server instance names that are available on the local PC?

Thanks a lot.

Prashanth Thurairatnam
  • 4,353
  • 2
  • 14
  • 17
Jameel
  • 1,126
  • 1
  • 14
  • 27
  • 2
    possible duplicate of [How to list available instances of SQL Servers using SMO in C#?](http://stackoverflow.com/questions/1130580/how-to-list-available-instances-of-sql-servers-using-smo-in-c) – Remus Rusanu May 28 '12 at 08:10

3 Answers3

19
string myServer = Environment.MachineName;

DataTable servers = SqlDataSourceEnumerator.Instance.GetDataSources();
for (int i = 0; i < servers.Rows.Count; i++)
{
    if (myServer == servers.Rows[i]["ServerName"].ToString()) ///// used to get the servers in the local machine////
     {
         if ((servers.Rows[i]["InstanceName"] as string) != null)
            CmbServerName.Items.Add(servers.Rows[i]["ServerName"] + "\\" + servers.Rows[i]["InstanceName"]);
         else
            CmbServerName.Items.Add(servers.Rows[i]["ServerName"].ToString());
      }
  }
Uday Teja
  • 263
  • 3
  • 15
Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
4
        //// Retrieve the enumerator instance, and then retrieve the data sources.
        SqlDataSourceEnumerator instance = SqlDataSourceEnumerator.Instance;
        DataTable dtDatabaseSources = instance.GetDataSources();

        //// Populate the data sources into DropDownList.            
        foreach (DataRow row in dtDatabaseSources.Rows)
            if (!string.IsNullOrWhiteSpace(row["InstanceName"].ToString()))
                Model.DatabaseDataSourceNameList.Add(new ExportWizardChooseDestinationModel
                {
                    DatabaseDataSourceListItem = row["ServerName"].ToString()
                        + "\\" + row["InstanceName"].ToString()
                });
Rashad Valliyengal
  • 3,132
  • 1
  • 25
  • 39
2

try

SqlDataSourceEnumerator.Instance.GetDataSources()
Karthik
  • 2,391
  • 6
  • 34
  • 65