Get All Instances of SQL Server in C#

We'll be using SQL SMO(SQL Management Objects)
First of All, you need to add a reference to the Microsoft.SqlServer.smo.dll file which is located in:
 
For 64-bit Windows 7:
[Your drive]:\Program Files (x86)\Microsoft SQL Server\100\SDK\Assemblies\Microsoft.SqlServer.Smo.dll
 
For 32-bit Windows 7:
[Your drive]:\Program Files\Microsoft SQL Server\100\SDK\Assemblies\Microsoft.SqlServer.Smo.dll
 
Now that we've added it to our project, we can start coding!
 
Add a ListBox control to your project:
  1. DataTable dataTable = SmoApplication.EnumAvailableSqlServers(true);  
  2. listBox1.ValueMember = "Name";  
  3. listBox1.DataSource = dataTable; 
By running this code alone,you'll get all the available sql servers inside your listbox control.
 
art3.png
 
Ok, let's develop it further. Let's see what databases our instances have
 
So to do this, you need to add another ListBox.Then in your listbox1's selectedindexchanged event, you need to check which server selected. So you need to create a server object first.
 
After this, you'll iterate through this server to populate all the databases in the newly created Listbox.
 
Here is the code to do that:
  1. listBox2.Items.Clear();  
  2. if (listBox1.SelectedIndex != -1) {  
  3.     string serverName = listBox1.SelectedValue.ToString();  
  4.     Server server = new Server(serverName);  
  5.     try {  
  6.         foreach(Database database in server.Databases) {  
  7.             listBox2.Items.Add(database.Name);  
  8.         }  
  9.     } catch (Exception ex) {  
  10.         string exception = ex.Message;  
  11.     }  
After we run the project we'll be getting our Databases.
 
art4.png
 
Hope it helps!