JJ.
JJ.

Reputation: 9950

How do I get a list of SQL Servers available on my network?

I'm trying this but I'm not sure how to proceed. Can you give me a hand?

SqlDataSourceEnumerator instance = SqlDataSourceEnumerator.Instance;
DataTable table = instance.GetDataSources();

foreach (var row in table.Rows)
{
     foreach (var column in table.Columns)
     {
          ddlPublisherServer.Items.Add(???);
     }
}

Where ??? = SQL Server Name.

How would I go about extracting the sql server name from the table?

I'm working in ASP .NET with C#.

Upvotes: 2

Views: 15926

Answers (1)

Brad Christie
Brad Christie

Reputation: 101594

Well, if wanted to see all available information, you can iterate over the columns available:

DataTable dt = SqlDataSourceEnumerator.Instance.GetDataSources();
foreach (DataRow dr in dt.Rows)
{
    foreach (DataColumn col in dt.Columns)
    {
        Console.WriteLine("{0,-15}: {1}", col.ColumnName, dr[col]);
    }
    Console.WriteLine();
}

Which would show something like:

ServerName     : COMPUTER1
InstanceName   : SQLEXPRESS
IsClustered    : No
Version        : 9.00.4035.00

So, to answer your question:

ddlPublisherServer.Items.Add(row[table.Columns["ServerName"]]);

Full Code:

DataTable table = System.Data.Sql.SqlDataSourceEnumerator.Instance.GetDataSources();
foreach (DataRow server in table.Rows)
{
  ddlPublisherServer.Items.Add(server[table.Columns["ServerName"]].ToString());
}

Upvotes: 10

Related Questions