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

这段代码只给了我计算机的名称。我想给我带有 sqlserver 名称的计算机名。例如这段代码给了我 anfd-pc 但我需要例如 anfd-pc\sqlexpress 或 anfd-pc\zarnegar

4

2 回答 2

3

ServerName您从中获取的表中的列GetDataSources()正是服务器名称。您还可以从列中 获取实例名称。有关其他可用选项,请参阅 MSDNInstanceName

所以你的代码会变成这样:

cmbshowallsqlserver.Items.Add(
    string.Format(@"{0}\{1}",
                  server[table.Columns["ServerName"]],
                  server[table.Columns["InstanceName"]])
);
于 2013-05-01T17:13:57.413 回答
1
DataTable table = SqlDataSourceEnumerator.Instance.GetDataSources();

foreach (DataRow server in table.Rows)
{
    string servername = server[table.Columns["ServerName"]].ToString();

    // you can get that using the instanceName property 
    string instancename = server[table.Columns["InstanceName"].ToString();

    //and version property tells you the version of sql server i.e 2000, 2005, 2008 r2 etc
    string sqlversion = server[table.Columns["Version"].ToString();

    //to form the servername you can combine the server and instancenames as
    string sqlserverfullname = String.Format("{0}\{1}",servername, instancename);

    cmbshowallsqlserver.Items.Add(sqlserverfullname);
}
于 2013-05-01T17:13:37.820 回答