Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / database / SQL-Server

How to enum SQL Server instances in network

4.96/5 (9 votes)
13 Feb 2013CPOL 62.5K   2.5K  
This tip is desired for those who want to list all available SQl Server instances that are in a network.

Introduction

Sometimes we need to list all available SQL Server instances in LAN to gain information about them. For example, it's useful when we need to write a custom installer for our database.

This tip shows us how to solves this problem. 

Using the code  

The code is as simple as it's possible Wink | ;)

What you need to test the code? 

  1. Create new project (windows application), 
  2. Add: 
    • 1 Label
    • 1 ComboBox (change it name to: CmbSQLInstance
    • 1 DataGridView  (change it name to: DGVSQLInstances)

Before you start coding, you need to set reference to  System.Data.Sql namespace (as is described here: http://msdn.microsoft.com/en-us/library/vstudio/wkze6zky%28v=vs.80%29.aspx).

VB
'declare variables
Dim dt As Data.DataTable = Nothing, dr As Data.DataRow = Nothing

Try
    'get sql server instances in to DataTable object
    dt = Sql.SqlDataSourceEnumerator.Instance.GetDataSources()

    'load data in to ComboBox
    For Each dr In dt.Rows
        Me.CmbSQLInstance.Items.Add(dr.Item(0).ToString)
    Next
    'load data in to DataGridView
    Me.DGVSQLInstances.DataSource = dt

Catch ex As System.Data.SqlClient.SqlException
    MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Error!")

Catch ex As Exception
    MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Error!")

Finally
    'clean up ;)
    dr = Nothing
    dt = Nothing
End Try 

Alternatives

History

  • 2013/02/11 - First version.
  • 2013/02/13 - source files added

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)