如何使用 vb.net 在 web.config 文件中的 Web 表单中引用连接字符串

How to Reference Connection String in web form that is in web.config file using vb.net

我正在启动一个新系统,我已经将连接字符串存储在我的 web.config 文件中。我现在想在我的 Web 表单中使用该连接字符串。怎么引用呢

这是我 web.config 文件中的内容

  <connectionStrings>
<add name="XX" connectionString="server=XX;UID=XX;PWD=XX;Database=XX" />
    <add name="XXX" connectionString="server=XX;UID=XX;PWD=XX;Database=XX" />
  </connectionStrings>

这是我希望在 using 语句或其他内容中使用连接字符串的 Web 表单,而不必在每个表单中每次都打开和关闭连接。

Protected Sub btnSearchEmployee_Click(sender As Object, e As EventArgs) Handles btnSearchEmployee.Click

        Dim conn As New SqlConnection("server=XX; Database= XX; Integrated Security = XX")
        Dim cmd As New SqlCommand("SELECT * FROM EmployeeCodes WHERE (FirstName LIKE '%' + @firstname + '%') OR (Code = @code) ", conn)

        cmd.Parameters.Add("@firstname", SqlDbType.VarChar).Value = txtSearchEmployee.Text
        cmd.Parameters.Add("@code", SqlDbType.VarChar).Value = txtSearchEmployee.Text

        Dim adapter As New SqlDataAdapter(cmd)
        Dim tbl As New DataTable()

        adapter.Fill(tbl)

        txtName.Text = ""
        txtSurname.Text = ""
        txtIDNo.Text = ""
        txtCostCentre.Text = ""
        txtDepartment.Text = ""
        txtClockNo.Text = ""



        If tbl.Rows.Count() > 0 Then

            txtName.Text = tbl.Rows(0)(5).ToString()
            txtSurname.Text = tbl.Rows(0)(6).ToString()
            txtIDNo.Text = tbl.Rows(0)(8).ToString()
            txtCostCentre.Text = tbl.Rows(0)(8).ToString()
            txtDepartment.Text = tbl.Rows(0)(8).ToString()
            txtClockNo.Text = tbl.Rows(0)(1).ToString()

            lblSearchEmployee.Visible = False


        Else

            lblSearchEmployee.Visible = True

        End If



    End Sub

你可以写

Dim conn As New SqlConnection(ConfigurationManager.ConnectionStrings("XX").ToString())

如果我遗漏了什么,请使用 VB.net 检查语法。

您可以通过传递您在 web.config 文件中设置的名称来使用任何连接字符串