Using a connection string from web.config

Ok. I thought this was going to be easy but it is turring out to be harder than I expected.

I want to use a database connection string from the web.config file.
If I use a sqldataadapter and configure a connection then the page works fine.
If i attempt to use the information from the web.config file I get the following message when attempting to connect to the DB.
The ConnectionString property has not been initialized.
Here is the code that I am using to establish the connection.

Imports System.Web.Security
Imports System.Data.SqlClient
Public Class WebForm1
Inherits System.Web.UI.Page
#Region " Web Form Designer Generated Code "
'This call is required by the Web Form Designer.
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
Me.SqlDataAdapter1 = New System.Data.SqlClient.SqlDataAdapter
Me.SqlSelectCommand1 = New System.Data.SqlClient.SqlCommand
'Me.SqlConnection1 = New System.Data.SqlClient.SqlConnection
Me.sqlconn = New SqlConnection
Me.SqlDataAdapter1.SelectCommand = Me.SqlSelectCommand1
Me.SqlDataAdapter1.TableMappings.AddRange(New System.Data.Common.DataTableMapping() {New System.Data.Common.DataTableMapping("Table", "dbo_select_login_sp", New System.Data.Common.DataColumnMapping() {New System.Data.Common.DataColumnMapping("username", "username"), New System.Data.Common.DataColumnMapping("password", "password"), New System.Data.Common.DataColumnMapping("firstname", "firstname"), New System.Data.Common.DataColumnMapping("lastname", "lastname"), New System.Data.Common.DataColumnMapping("grpcode", "grpcode")})})
Me.SqlSelectCommand1.CommandText = "dbo.[select_login_sp]"
Me.SqlSelectCommand1.CommandType = System.Data.CommandType.StoredProcedure
Me.SqlSelectCommand1.Connection = sqlconn
Me.SqlSelectCommand1.Parameters.Add(New System.Data.SqlClient.SqlParameter("@RETURN_VALUE", System.Data.SqlDbType.Int, 4, System.Data.ParameterDirection.ReturnValue, False, CType(0, Byte), CType(0, Byte), "", System.Data.DataRowVersion.Current, Nothing))
Me.SqlSelectCommand1.Parameters.Add(New System.Data.SqlClient.SqlParameter("@username", System.Data.SqlDbType.VarChar, 10))
Me.SqlSelectCommand1.Parameters.Add(New System.Data.SqlClient.SqlParameter("@password", System.Data.SqlDbType.VarChar, 6))
Me.sqlconn.ConnectionString = ConfigurationSettings.AppSettings("ConnectionString")

End Sub
Protected WithEvents txtuser As System.Web.UI.WebControls.TextBox
Protected WithEvents TextBox2 As System.Web.UI.WebControls.TextBox
Protected WithEvents Label1 As System.Web.UI.WebControls.Label
Protected WithEvents Label2 As System.Web.UI.WebControls.Label
Protected WithEvents Button1 As System.Web.UI.WebControls.Button
Protected WithEvents lblmessage As System.Web.UI.WebControls.Label
Protected WithEvents SqlDataAdapter1 As System.Data.SqlClient.SqlDataAdapter
Protected WithEvents SqlSelectCommand1 As System.Data.SqlClient.SqlCommand
Protected WithEvents SqlConnection1 As System.Data.SqlClient.SqlConnection
Dim sqlconn As SqlConnection

'NOTE: The following placeholder declaration is required by the Web Form Designer.
'Do not delete or move it.
Private designerPlaceholderDeclaration As System.Object
Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
'CODEGEN: This method call is required by the Web Form Designer
'Do not modify it using the code editor.
End Sub
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If Page.IsPostBack Then
validateuser(txtuser.Text, TextBox2.Text)
End If
End Sub

Sub validateuser(ByVal username, ByVal password)
Dim dr As SqlDataReader
SqlSelectCommand1.Parameters("@username").Value = username
SqlSelectCommand1.Parameters("@password").Value = password
dr = SqlSelectCommand1.ExecuteReader()
If dr.Read Then
FormsAuthentication.SetAuthCookie(username, False)
Response.Cookies.Add(New HttpCookie("firstname", dr("firstname")))
Response.Cookies.Add(New HttpCookie("lastname", dr("lastname")))
Response.Cookies.Add(New HttpCookie("group", dr("grpcode")))
lblmessage.Text = "Authentication"
lblmessage.Text = "NO GO"
End If
Catch ex As Exception
lblmessage.Text = ex.Message
End Try
End Sub
#End Region

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
validateuser(txtuser.Text, TextBox2.Text)
End Sub
End Class

Anyone have any ideas why I keep getting this message. Am I declaring the Sqlconnection wrong?
7/27/2004 1:22:45 PM 91979 articles. 3 followers. Follow

1 Replies

Similar Articles

[PageSpeed] 32

Try to use debugger and check if line

Me.sqlconn.ConnectionString = ConfigurationSettings.AppSettings("ConnectionString")
works as it suppose to. If not, check Web.config, may be ConnectionString is misplaced or misspelled.

Leon Langleyben


7/27/2004 2:06:58 PM

Similar Artilces:

Why we use Web.Config File for connection string wether we can use class Library for get connection for whole web Application
 Why we use Web.Config File for connection string wether we can use class Library for get connection for whole web Application  please help me? Friend, Web.config has its own advantages. 1) Web.Config is used to store the important information like connections strings that it can be modified even after the code has been    deployed to the server without compiling the entire application again. 2) Since it is a XML file, there is no need of building the project of you are going to change the connection strings.   If you go for the class files,...

Get connection string from web.config and secure that connection
Hi, I store my connection string on my web.config file, and I want to create a new connection on c# like:SqlConnection con = new SqlConnection();con.ConnectionString= //connection string on web.config fileAfter that, The connection string on the web.config file is in clear text and I want to make it secure but easy to work because this job is to deliver until friday. Is there any easy way to do this and keep the possibility of creating a new connection and making reference to this connection string without need for decrypt data?Thanks, please help!Best regards,David Ribeiro After reading t...

OLEDB Connection problem using Connect String from Web.config
Hi,Cananybody tell me why I am getting the following error for the following code below An OLE DB Provider was not specified in the ConnectionString.  An example would be, 'Provider=SQLOLEDB;'. "Ppp" is a connection defined in Web.config which works with SqlDatasource in the application. DataSet RunQuery(String QueryString) { String ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["Ppp"].ConnectionString; OleDbConnection DBConnection = new OleDbConnection( ConnectionString); OleDbDataAdapter DBAdapter; DataSet ResultsDataSet = new DataSet(); M....

How do I use my web.config connection string in my DataAdapter/Connection that I created with drag/drop and data binding
This is a little hard to put into words... I have a form with a number of textbox fields on it that are bound to a data adapter. The data adapter and it's sql connection were created by dragging the objects onto the screen from the toolbox (not in code). I open connections in other places and use my connection string in web.config for those. The on-screen sql connection object doesn't seem to allow me to just fill in the function that pulls my conn string from web.config so in page.load, I set it's connection string to my connection string. Does the page load fire before the connect...

how to get the connection string from the web.config?
how do i get a connection string from the web.config file? I keep getting Error Reading the database.Instance failure.   when i use string connectionString = WebConfigurationManager.ConnectionStrings["conString"].ConnectionString;   but this same connectiong string works when i hard code it into the string variable....   Thankspwpaust Have a look at this thread. Hi   I read that link, thanks but it still didn't is the code... <configuration> <appSettings/>  <connectionStrings&g...

I have a connection string defined in the web.config file and as you know it is given a name.How can I reference such a connection string from a web form using the name given in the web.config file?What I actually do is to copy and paste the whole string in my web forms as follows:Dim pgConn As New PgSqlConnection("User Id=postgres;Password=p@ssw0rd;Host=localhost;Database=e-restdelivery;Persist Security Info=True;Schema=restaurant;Protocol=2")This method is not efficient because if the string changes I have to modify every web form where a connection string is locat...

How to use Connection String from Web Config
Hi All, How do I use the Web Config connection string in code behind? What is the syntax Dim oCnn As New SqlConnection= ???? Thanks    Dim oCnn As New SqlConnectionoCnn.ConnectionString = ConfigurationManager.ConnectionStrings("MyConnectionString").ConnectionStringDont forget to import System.Configuration Regards Mike [MVP - ASP/ASP.NET]My site...

Trying to use web.config for connection strings
I am trying to use a web.config file to store my connection string for my web app, but I am unable to retrieve the stored values, here is the code to my web.config and the sample page I'm testing. Sample Page dim strSql as string dim ds as dataset dim da as oledbDataAdapter dim Conn as string dim myconn as oledbConnection sub page_load(Sender As Object, E As EventArgs) lblDate.text = "Today's Date is: " & GridLoad() End sub Public sub GridLoad() strSql = &qu...

How to use the connection string from the web.config with a method?
I have been trying to create the connection and then pass it around with no luck. Instead I've been able to just keep recreating it with each method on the page. I don't know why when I create a variable in the page_load event it just doesn't get seen inside of methods. If I put the variable holding the connection string in the page before the page_load event, I think the page class?, it still doesn't work. Could someone give me a heads up on why please? THank you so much in advance.  1 using System;2 using System.Data;3 using System.Configuration;4 usin...

Getting a Connection String from my Web Config file
Is there a way that I can create a class or a generally available function in Visual Web Developer Express that will return the connection string that I stored in the Web config file and/or a new connection based on that string?Any help appreciated.Regards,Roger Swetnam  in the Class where all Data Base logic is implementd define a Method like this: public string GetConnectionString(string stringName) { return ConfigurationManager.ConnectionStrings[stringName].ConnectionString; }  where stringName is the Name of your desired Connection string. its a Generic...

Updating Web.Config( ^SqlConnectionString^ was not found in web.config. Connection String was not updated).
hi ppl i installed the forum and when it was fininshed im not getting the fierst screen. when i wrote it myself on the explorer http://localhost/Forums it gave an error like this:::::::::::::::    Login failed for user 'amit'. Reason: Not associated with a trusted SQL Server connection Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Data.SqlClient.SqlException: Login failed for user 'amit'. Reason:...

app.config connection string not being read
I have a Web app that has a UI Website Project and a DB dataset/db project. I am running SQL Server 2005 Express on my localhost for development purposes. I have the connectionstring for the DB in the DB projects app.config. The site is running perfectly on my localhost, but when I deploy the site to the review server and change the app.config's connectionstring accordingly a connection to the DB cannot be established. I then tried changing all the db names, usernames, password to jibberish in my app.config file on my localhost and running AND THE SITE STILL RAN ON LOCALHOST. For so...

using membership but keep connection strings out of web.config ?
Im using membership in my application, but I dont want to define the connection string in the config file also.  I want to store itelsewhere, then when the app starts up, load it and set this value.  Is this a good approach ?  For example, in your global.asax, application_start event you could load your connection string from a class property, then with System.Web.Configuration.WebConfigurationManager you can get the connection string name, and update its value.  Will this work ? If you want to store the connectionstring value elsewhere for security reasons, you might t...

How to use a connection string already defined in web.config?
Hi, I am writing an event procedure for a button's click event, and want to use a connection string which is already defined the web.config file.  How can I do that from the even procedure?Below is the content taken form my web.config file:<add name="NorthwindConnectionString" connectionString="Data Source=CPQ1;Initial Catalog=Northwind;Integrated Security=True"   providerName="System.Data.SqlClient" />David As long as this is under  web.config as <connectionStrings>  you can just refer to it in code as : <asp:SqlDataSource ID="SqlDataSource1" run...

Web resources about - Using a connection string from web.config -

Connection - Wikipedia, the free encyclopedia
Text is available under the Creative Commons Attribution-ShareAlike License ;additional terms may apply. By using this site, you agree to the ...

iMedia Connection: Interactive Marketing News, Features, Podcasts and Video -
High-quality data, if not used properly, can still lead marketers to make bad decisions. Consider these common ways that numbers are used to ...

HTTP persistent connection - Wikipedia, the free encyclopedia
... tacked on to an existing protocol. If the browser supports keep-alive, it adds an additional header to the request: Following this, the connection ...

CareerSonar Turns Facebook Friends Into Job Connections
Looking for a job ? Among your Facebook friends lies the potential for employment. CareerSonar , a new service, brings together a person’s connections ...

Ben Garcia gives Penrith Panthers a new French connection
Should he jag a game in the NRL, Ben Garcia will become just the third genuine French import to do so.

Man Charged With Aggravated Arson In Connection To Columbus Warehouse Fire
Police have charged 30-year-old Robin Toms with aggravated arson.

Facebook becomes more adept at dealing with crappy connections
... to get a decent phone signal to allow you to post a photo of your meal. Joking aside, in countries where people are struggling with 2G connections ...

Adam Savage from 'MythBusters' has an incredible connection to the 'Star Wars' franchise
Adam Savage, co-host of the popular " MythBusters " television show, soured on the plot of "Interstellar." But when it comes to the newest films ...

French authorities detain suspects in connection to attacks 10 months apart
CNN French authorities detain suspects in connection to attacks 10 months apart CNN A forensic scientist works near a Paris cafe on Saturday, ...

UK Police Make Arrest in Connection With VTech Hacking
British law enforcement officials arrest a 21-year-old man in connection with attack on toy maker VTech that exposed 6 million parents and children ...

Resources last updated: 12/25/2015 10:55:35 AM