0

I am starting a new system and i have already stored the connection string in my web.config file. I now want to use that connection string in my web forms. How do i reference it.

This is what I have in my web.config file

  <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>

This a web form that i wish to use the connection string maybe in a using statement or something, without having to open and close the connection each time in each form.

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

1 Answer 1

1

You can write

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

Please check syntax with VB.net if I miss something.

You can use any of the connection string by passing name of that which you have set in web.config file

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks so much @Kevin Shah it worked. So i do not need to use conn.open() and conn.close() in my code as this line already caters for that ?
no you need to call open() and close() as this just set the connection string. To let SqlConnection know which database it has to connect
For that you can create a class library to handle conenction through out the application instead of initializing it every where in page.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.