您的当前位置:首页正文

asp.net得到本机数据库实例的两种方法代码

2022-06-15 来源:知库网

代码如下:
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
  protected void Page_Load(object sender, EventArgs e)
  {
    //方法1
    System.Data.DataTable table = System.Data.SqlClient.SqlClientFactory.Instance.CreateDataSourceEnumerator().GetDataSources();
    GridView1.DataSource = table;
    GridView1.DataBind();
    //得到本机的
    foreach (System.Data.DataRow row in table.Rows)
    {
      if (row[0].ToString().ToUpper().Equals(System.Net.Dns.GetHostName().ToUpper()))
      {
        Response.Write("<li>" + row[1]);
      }
    }
    //方法2
    //需要引用Microsoft.SqlServer.Smo.dll
    GridView2.DataSource = Microsoft.SqlServer.Management.Smo.SmoApplication.EnumAvailableSqlServers(true);
    GridView2.DataBind();
  }
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
  <title></title>
</head>
<body>
  <form id="form1" runat="server">
  <asp:GridView ID="GridView1" runat="server">
  </asp:GridView>
  <asp:GridView ID="GridView2" runat="server">
  </asp:GridView>
  </form>
</body>
</html>
显示全文