Rabeea qabaha Rabeea qabaha - 3 months ago 7
Vb.net Question

Error when I add connection string in a UserControl

I am facing a weird problem, I am trying to create Usercontrol (Add_companies)and add it to panel
Everything work fine but when I add the connection to the user control I face this error :

The variable 'Add_companies1' is either undeclared or was never assigned.

And this is my connection:

Protected configuracion As ConnectionStringSettings = ConfigurationManager.ConnectionStrings("Conn")
Dim Conn As New SqlConnection(configuracion.ConnectionString)
Public Cmd As SqlCommand


Error one image

where the error code must be

and when i go to the code line error there's nothing.

Answer
Protected configuracion As ConnectionStringSettings = ConfigurationManager.ConnectionStrings("Conn")
Dim Conn As New SqlConnection(configuracion.ConnectionString)
Public Cmd As SqlCommand

You indicate that you placed this code in your UserControl and now the Form designer is throwing errors. The VS IDE is loading and running an instance of the usercontrol when it is placed on the design surface.

These three lines of code would have to be placed at the class level to support the Protected and Public access modifiers. The issue is that the designer is not able to retrieve ConfigurationManager.ConnectionStrings("Conn") so configuracion is null when it is used in Dim Conn As New SqlConnection(configuracion.ConnectionString).

When you use the syntax: Dim var as New Something() at the class level, the compiler converts that to Dim var as Something and places var = New Something() into the class constructor (Sub New) code.

To fix this problem you need to prevent code that will through an error while in design mode from executing. All controls have a Boolean property named DesignMode for this purpose. Note that DesignMode will not be valid if used in the constructor code, so trying to use it there will fail.

Imports System.Configuration
Imports System.Data.SqlClient

Public Class Add_companies
    Protected configuracion As ConnectionStringSettings
    Private Conn As SqlConnection
    Public Cmd As SqlCommand

    Private Sub Add_companies_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        If Not Me.DesignMode Then
            configuracion = ConfigurationManager.ConnectionStrings("Conn")
            Conn = New SqlConnection(configuracion.ConnectionString)
        End If
    End Sub
End Class
Comments