// Web.Config <?xml version="1.0" encoding="utf-8"?> <!-- 有关如何配置 ASP.NET 应用程序的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkId=169433 --> <configuration> <system.web> <compilation debug="false" targetFramework="4.5" /> <httpRuntime targetFramework="4.5" /> </system.web> <appSettings> <add key="connectionString" value="server=.;database=stuTest; uid=sa;pwd=123456"/> </appSettings> </configuration> // 获取配置文件信息 using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.Data.SqlClient; using System.Configuration; public partial class GridViewPage_One : System.Web.UI.Page { //第一种写法已经过时,会提示错误信息将ConfigurationSettings改成ConfigurationManager
//然后在命名空间中加入using System.Configuration; // private string connectionString = ConfigurationSettings.AppSettings["connectionString"].ToString(); private string connectionString = ConfigurationManager.AppSettings["connectionString"].ToString(); protected void Page_Load(object sender, EventArgs e) { if (!this.IsPostBack) { FillList(); } } private void FillList() { string selectSql = "select * from Stu"; SqlConnection con = new SqlConnection(connectionString); SqlCommand cmd = new SqlCommand(selectSql,con); SqlDataAdapter adapter = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); try { con.Open(); adapter.Fill(ds,"Students"); this.GridView1.DataSource = ds.Tables["Students"].DefaultView; this.GridView1.DataBind(); } catch(Exception err) { throw err; } } }