In c#2010, how do you save and access the connection string for the database?
To add the App. Config file under WinForm, add the Web. config file under ASP.
1. After opening the configuration file, add the relevant code as follows:
<?xml version="1.0" encoding="utf-8"?><configuration> <connectionstrings > <add name="myconn" connectionstring="Data source=.;i Nitial Catalog=northwind; Persist Security info=true; User Id=sa; password="/> </connectionStrings></configuration>
2. Add a using System.Configuration, and right-click on the item "Add Reference"->. NET component "Using Configuration"
If you do not add references to the component, subsequent code compilation is not possible.
3. The following is the code to read the data
Privatevoid Button1_Click (Objectsender, EventArgs e) {String connstr = configurationmanager.connectionstrings["myconn"]. ConnectionString; using (SqlConnection conn = new SqlConnection (connstr)) {SqlCommand comm = new SqlCommand ("Selec T FirstName from Employees", conn); Conn. Open (); SqlDataReader SDR = Comm. ExecuteReader (); while (SDR. Read ()) {listBox1.Items.Add (sdr[0]. ToString ()); } } }