views:

219

answers:

2

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?

+2  A: 

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.

Joseph
Ok so does that mean if I place the MyProgram.exe and the MyProgram.exe.config together on my desktop it will work fine ?
JonH
Ok you are right then it works fine...I guess I see why you have to package the application :). Thank you!
JonH
It should. I'm surprised the My.Settings version worked without any other file.
Joel Coehoorn
@JonH No problem =)
Joseph
@Joel - I think it is because the classes generated behind the scenes for the My.Settings have default values in the code, so if the config file is not present, it uses the default. I'm not 100% sure about this though.
Chris Dunaway
+1  A: 

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.

TheVillageIdiot
Ok yep you are right as well :). Thank you.
JonH