利用 System.Data.Sql.SqlDataSourceEnumerator 類別可掃描網路內可用的 SQL Server 執行個體,並綁定至 DropDownList 供使用者選擇。
<asp:DropDownList ID="DropDownListInstance" runat="server"></asp:DropDownList>
protected void Page_Load(object sender, EventArgs e) {
DataTable dataTable = SqlDataSourceEnumerator.Instance.GetDataSources();
foreach (DataRow dr in dataTable.Rows) {
string serverName = dr["ServerName"].ToString();
string instanceName = dr["InstanceName"].ToString();
if (string.IsNullOrEmpty(instanceName)) {
DropDownListInstance.Items.Add(serverName);
} else {
DropDownListInstance.Items.Add(serverName + "\\" + instanceName);
}
}
}
筆者筆電安裝 SQL Server 2012 與 2008 R2 兩個實例,下拉清單正確顯示兩項:

System.Data.dll