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 using System.Collections;
5 using System.Web;
6 using System.Web.Security;
7 using System.Web.UI;
8 using System.Web.UI.WebControls;
9 using System.Web.UI.WebControls.WebParts;
10 using System.Web.UI.HtmlControls;
11 using System.Data.SqlClient;
12 13 public partial class userpage : System.Web.UI.Page
14 {
15 //string crrntusr = String.Empty;
16 //string crrntpass = String.Empty;
17 18 protected void Page_Load(object sender, EventArgs e)
19 {
20 //if (!IsPostBack) 21 if (Page.PreviousPage != null)
22 {
23 usrNmeLbl.Text = PreviousPage.CurrentUser;
24 psswrdLbl.Text = PreviousPage.CurrentPass;
25 if (usrNmeLbl.Text != null)
26 {
27 loadFamHist();
28 }
29 else 30 Response.Redirect("login.aspx");
31 }
32 else 33 {
34 usrNmeLbl.Text = "Please log in";
35 psswrdLbl.Visible = false;
36 Label4.Visible = false;
37 }
38 }
39 40 public void loadFamHist()
41 {
42 //Read the connection string from Web.config 43 string connectionString = ConfigurationManager.ConnectionStrings["thyTreeConnectionString"].ConnectionString;
44 //Initialize connection 45 SqlConnection conn = new SqlConnection(connectionString);
46 conn.Open();
47 48 //comm.CommandText = "SELECT * FROM UsrTbl, RelativeTable, IP_Table WHERE RelativeTable.UserID IN (SELECT UserID FROM UsrTbl WHERE UserName = @usrnmeLbl)"; 49 SqlCommand comm = new SqlCommand("SELECT * FROM UsrTbl, RelativeTable, IP_Table WHERE RelativeTable.UserID IN (SELECT UserID FROM UsrTbl WHERE UserName = @usrnmeLbl)", conn);
50 comm.Parameters.AddWithValue("@usrnmeLbl", usrNmeLbl.Text);
51 52 SqlDataReader reader = comm.ExecuteReader();
53 //Check to see if the reader has data(Did the username exist in the database? We must check this 54 if (reader.Read() != false)
55 {
56 while (reader.Read())
57 {
58 string usr = reader["UserName"].ToString();
59 usr = usr.TrimEnd();
60 string pss = reader["Password"].ToString();
61 pss = pss.TrimEnd();
62 //take the read data from the reader and display it for testing purposes
63 //readDB_Lbl.Text = (String.Format("{0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}, {9}, {10}, {11}, {12}, {13}, {14}, {15}, {16}, {17}, {18}, {19}, {20}, {21}, {22}",
64 //reader[0], reader[1], reader[2], reader[3], reader[4], reader[5], reader[6], reader[7], reader[8], reader[9], reader[10], reader[11], reader[12], reader[13], reader[14], reader[15], reader[16], reader[17], reader[18], reader[19], reader[20], reader[21], reader[22]));
65 if (usrNmeLbl.Text == usr)
66 {
67 if (psswrdLbl.Text == pss)
68 {
69 //read the column from the reader and cast it to String as some may contain null values 70 usrNmeLbl.Text = reader["FirstName"].ToString() + " ";
71 psswrdLbl.Text = reader["LastName"].ToString() + "<br />";
72 psswrdLbl.Text += "Place of Birth: " + reader["BirthPlace"].ToString() + "<br />";
73 psswrdLbl.Text += "<img src=" + reader["Photo"].ToString() + " />" + "<br />";
74 Label4.Text = "Your relatives: " + "<br />";
75 getRelatives();
76 }
77 //If password does not match 78 else 79 {
80 usrNmeLbl.Text = "You have not logged into a valid account. <br />Please try logging in.";
81 psswrdLbl.Visible = false;
82 Label4.Visible = false;
83 reader.Close();
84 conn.Close();
85 }
86 }
87 //break; //exit out of the loop since user found 88 }
89 }
90 //If the database doesn't return a valid user, but null 91 else 92 {
93 usrNmeLbl.Text = "You have not logged into a valid account. <br />Please try logging in.";
94 psswrdLbl.Visible = false;
95 Label4.Visible = false;
96 reader.Close();
97 conn.Close();
98 }
99 }
100 //private void getRelatives(sqlCommand comm) 101 private void getRelatives()
102 {
103 //Read the connection string from Web.config 104 string connectionString = ConfigurationManager.ConnectionStrings["thyTreeConnectionString"].ConnectionString;
105 //Initialize connection 106 SqlConnection conn = new SqlConnection(connectionString);
107 conn.Open();
108 109 SqlCommand comm = new SqlCommand("SELECT Relation, RelativeFN, RelativeLN, RelativeBP, RelativeEmail, RelativeIM FROM RelativeTable WHERE RelativeTable.UserID IN (SELECT UserID FROM UsrTbl WHERE UserName = @usrnmeLbl)", conn);
110 comm.Parameters.AddWithValue("@usrnmeLbl", usrNmeLbl.Text);
111 112 SqlDataReader reader = comm.ExecuteReader();
113 while (reader.Read())
114 {
115 Label4.Text += reader["Relation"].ToString() + ": ";
116 Label4.Text += reader["RelativeFN"].ToString() + "&lt;br />";
117 Label4.Text += reader["RelativeLN"].ToString() + "&lt;br />";
118 Label4.Text += reader["RelativeBP"].ToString() + "&lt;br />";
119 Label4.Text += reader["RelativeEmail"].ToString() + "&lt;br />";
120 Label4.Text += reader["RelativeIM"].ToString() + "&lt;br />";
121 }
122 reader.Close();
123 conn.Close();
124 }
125 126 //Clear all session variables
127 //Session.Clear();
128 //Removes a particular session variable
129 //Session.Contents.Remove("SomeSessionVariableName ");
130 }
131
  
0
foolios
6/23/2007 3:05:06 AM
asp.net.getting-started 91979 articles. 3 followers. Follow

3 Replies
564 Views

Similar Articles

[PageSpeed] 32

 http://www.dotnet-guide.com/configurationmanager-class.html


Hope That Helps
All that wander, are not lost...
What were we talkin bout
0
uncleb
6/23/2007 4:44:57 AM

hi.. here i can see that you are writing everything in presentation layer code..

you can define a public class with shared varible "cnstr" as connection string and can use in your code; where you want it..

 

Imports System.Data.SqlClient
Public class ConnectionStringClass
Public Shared cnstr as New SqlConnectionString(ConfigurationManager.ConnectionStrings["thyTreeConnectionString"].ConnectionString)
End Class 

 

now you can use "cnstr" as ConnectinStringClass.cnstr. be sure that you check the status of the connection each and every time before you use it. and close the connection when you dont need it. as because this is shared variable..

hope this helps./. 


Thanx,
[KaushaL] || BloG || Profile || Microsoft MVP

"I would love to change the world, but they won’t give me the source code"


Don't forget to click "Mark as Answer" on the post that helped you.
This credits that member, earns you a point and mark your thread as Resolved for the sake of Future Readers.
0
kaushalparik27
6/23/2007 5:56:26 AM

Thank you for this. 

0
foolios
6/23/2007 6:39:24 PM
Reply:

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 etc...so 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...

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

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 http://forums.asp.net/thread/1374383.aspx Have a look at this thread. Hi   I read that link, thanks but it still didn't work..here is the code... <configuration> <appSettings/>  <connectionStrings&g...

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

HOW TO USE THE CONNECTION STRING IN WEB.CONFIG
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...

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: " & date.now.tostring() GridLoad() End sub Public sub GridLoad() strSql = &qu...

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 - How to use the connection string from the web.config with a method? - asp.net.getting-started

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 - iMediaConnection.com
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/23/2015 4:12:21 AM