JonH
JonH

Reputation: 33143

My.Settings.MyConnectionString works but app.config dont?

I'm not a WinForms developer, but have been doing ASP.NET for quite some time. I have to write something in VB.NET that just pushes some simple data to a database. So I created the VB.NET WinForms app (Visual Studio 2005).

When I run the app it works fine for using:

    Dim conMyData As SqlConnection
    Dim cmdInsert As SqlCommand
    Dim isSaved As Boolean
    isSaved = True
    conMyData = Nothing

    Try
        conMyData = New SqlConnection(My.Settings.MyConnectionString)
        cmdInsert = New SqlCommand("insComputer2", conMyData)

It also works fine if I use:

    Dim conMyData As SqlConnection
    Dim cmdInsert As SqlCommand
    Dim isSaved As Boolean
    isSaved = True
    conMyData = Nothing
    Dim str As String = ConfigurationManager.ConnectionStrings("connect").ConnectionString

    Try
        conMyData = New SqlConnection(str)
        cmdInsert = New SqlCommand("insComputer2", conMyData)

That is, if I define the connection string inside of the properties of the project. If I build my project, snatch the .exe from the bin\debug folder and run it on my desktop, it works ONLY if I have the version that says My.Settings.MyConnectionString

Otherwise, if I use the other version where I am pulling the connection string from my app.config file it only works if I run the project through visual studio, it will not run by just opening up the .exe on my desktop. It syas something like ConnectionString not set, or sometimes it states object not set to an instance of something...

My question is: why does it work from within the project?

Is it because when I build the project it cannot reference that app.config file since I've moved it to my desktop?

Upvotes: 1

Views: 3490

Answers (2)

TheVillageIdiot
TheVillageIdiot

Reputation: 40507

you will need to copy the app.config (now YourProgramName.exe.config as written by @Joseph) to the folder (in this case desktop) where you put yur exe.

when you use My.Settings.MyConnectionString you are using the resource existing in the exe so it works.

Upvotes: 1

Joseph
Joseph

Reputation: 25513

You have to have an app.config file and specify the connection string in there.

When you compile, the app.config will roll up into MyProgram.exe.config file, so look for that file when you do your build.

Upvotes: 2

Related Questions