当前位置:编程学习 > C#/ASP.NET >>

.net在连接数据库的时候出现的问题!希望老师能帮我解决这个问题 谢谢了!

在执行index时在后台代码中,conn.open()出现异常 提示connectionstring未初始化 

web.config中的代码: 
<connectionStrings> 
<add name="connectionstring" connectionString="Server=win-ho0cs0gr0k6\sqlexpress;database=51aspxCar;User ID=sa;Password=123456;" providerName="System.Data.SqlClient"/> 
</connectionStrings> 

在index.aspx.cs中的代码: 
using System; 
using System.Collections; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Web; 
using System.Web.SessionState; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.Web.UI.HtmlControls; 
using System.Data.SqlClient; 
namespace car1 

// 
/// <summary> 
/// index 的摘要说明。 
/// </summary> 
public class index : System.Web.UI.Page 

protected System.Web.UI.WebControls.Label err; 
protected System.Web.UI.WebControls.Button login; 
protected System.Web.UI.WebControls.RequiredFieldValidator repw; 
protected System.Web.UI.WebControls.TextBox password; 
protected System.Web.UI.WebControls.RequiredFieldValidator reusername; 
protected System.Web.UI.WebControls.TextBox username; 
protected System.Web.UI.WebControls.Label Label1; 
protected System.Web.UI.HtmlControls.HtmlForm Form1; 

private void Page_Load(object sender, System.EventArgs e) 



// 在此处放置用户代码以初始化页面 



#region Web 窗体设计器生成的代码 
override protected void OnInit(EventArgs e) 

// 
// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。 
// 
InitializeComponent(); 
base.OnInit(e); 


/// <summary> 
/// 设计器支持所需的方法 - 不要使用代码编辑器修改 
/// 此方法的内容。 
/// </summary> 
private void InitializeComponent() 

this.login.Click += new System.EventHandler(this.login_Click); 
this.Load += new System.EventHandler(this.Page_Load); 


#endregion 

private void login_Click(object sender, System.EventArgs e) 


//检查帐号和密码 
if(this.username.Text=="user"&this.password.Text=="user") 

Session["S_username"]=""; 
Response.Redirect("main2.aspx"); 


string SqlConn = System.Configuration.ConfigurationSettings.AppSettings["connectionstring"]; 
SqlConnection Conn=new SqlConnection(SqlConn); 
Conn.Open(); --------------------编程问答-------------------- string SqlConn = ConfiurationManager.ConnectionStrings["connectionstring"].toString(); --------------------编程问答-------------------- <connectionStrings>  
<add name="connectionstring" connectionString="Server=win-ho0cs0gr0k6\sqlexpress;database=51aspxCar;User ID=sa;Password=123456;" providerName="System.Data.SqlClient"/>  
</connectionStrings> 

使用

string SqlConn = System.Configuration.ConfigurationManager.ConnectionStrings["connectionstring"].ConnectionString ;  

来读取

AppSettings是读取AppSettings的。
ConfigurationSettings是.net1.1的东西,后面的net版本里有它只是为了向前兼容性,最好使用ConfigurationManager
补充:.NET技术 ,  C#
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,