Per recuperare l'elenco dei server SQL presenti nella rete locale basta utilizzare la classe SqlDataSourceEnumerator.
Questa classe dispone del metodo .GetDataSources che genera una DataTable contenente le informazioni di tutte le istanze visibili di SQL Server 2000 o SQL Server 2005.
Basterà quindi leggere i dati della tabella generata per avere un elenco completo delle istanze SQL.
' VB
' Elenco delle istanze SQL nella rete.
Dim sqleNum As Sql.SqlDataSourceEnumerator = Sql.SqlDataSourceEnumerator.Instance
Dim dt As DataTable = sqleNum.GetDataSources
' Imposta la colonna da visualizzare tramite la ComboBox.
cmbServer.DisplayMember = "ServerName"
' Recupera il nome dell'eventuale istansa.
If dt.Rows.Count > 0 Then
For Each row As DataRow In dt.Rows
If Not String.IsNullOrEmpty(row("InstanceName").ToString) Then
dt.Columns("ServerName").ReadOnly = False
row("ServerName") = row("ServerName").ToString & "\" & row("InstanceName").ToString
End If
Next
Else
MessageBox.Show("Non è stato rilevato alcun server SQL nella rete.")
End If
' Imposta il datasource della combobox.
Me.cmbServer.DataSource = dt
// C#
// Elenco delle istanze SQL nella rete.
Sql.SqlDataSourceEnumerator sqleNum = Sql.SqlDataSourceEnumerator.Instance;
DataTable dt = sqleNum.GetDataSources;
// Imposta la colonna da visualizzare tramite la ComboBox.
cmbServer.DisplayMember = "ServerName";
// Recupera il nome dell'eventuale istansa.
if (dt.Rows.Count > 0) {
foreach (DataRow row in dt.Rows) {
if (!string.IsNullOrEmpty(row("InstanceName").ToString)) {
dt.Columns("ServerName").ReadOnly = false;
row("ServerName") = row("ServerName").ToString + "\\" + row("InstanceName").ToString;
}
}
}
else {
MessageBox.Show("Non è stato rilevato alcun server SQL nella rete.");
}
// Imposta il datasource della combobox.
this.cmbServer.DataSource = dt;
NB: La conversione del codice da VB a C# è stata effettuata tramite il convertitore segnalato in area Utility.
La DataTable bindata ad una ComboBox.
La DataTable bindata ad una DataGridView.