[英]System.NullReferenceException – Object reference not set to an instance of an object
[英]ASP.NET - System.NullReferenceException: Object reference not set to an instance of an object
我在笔记本电脑上创建了一个项目,它工作正常。
我将我的项目转移到另一台笔记本电脑,现在它给我一个System.NullReferenceException
错误。
不知何故,数据库没有建立,它给出了一个NULL异常。
我的代码:
public partial class registration : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
// error is here
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["registerationConnectionString"].ConnectionString);
conn.Open();
string chekuser = "select count(*) from userdata where uname='" + TextBoxUN.Text + "'";
SqlCommand com = new SqlCommand(chekuser, conn);
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
if (temp == 1)
{
Response.Write("User already Exist: ");
}
conn.Close();
}
}
}
WEB.CONFIG
<configuration>
<appSettings/>
<system.web>
<compilation debug="true" targetFramework="4.0"/>
<httpRuntime/>
</system.web>
</configuration>
由于此行发生错误:
SqlConnection conn =
new SqlConnection(ConfigurationManager.ConnectionStrings
["registerationConnectionString"]
.ConnectionString);
您应该假设ConfigurationManager.ConnectionStrings
为null,并查找可能未正确复制的配置文件。 当你尝试.ConnectionString
从索引访问.ConfigurationManager.ConnectionStrings
返回null
,你还没有配置一个在你的web.config
。 在web.config
查找connectionStrings
部分。
更新
由于您已经提供了web.config
只需根据需要添加connectionStrings
:
<configuration>
<connectionStrings>
<add name="registerationConnectionString"
connectionString="Data Source=.;Initial Catalog=DBNAME;Integrated Security=True;Connect Timeout=15;" />
</connectionStrings>
<appSettings/>
<system.web>
<compilation debug="true" targetFramework="4.0"/>
<httpRuntime/>
</system.web>
</configuration>
您在web.config文件中没有任何连接字符串,其名称为= registerationConnectionString
因此ConfigurationManager.ConnectionStrings["registerationConnectionString"]
为我们提供了null值,然后当我们想要获取null的ConnectionString
时,它给出了System.NullReferenceException
。 您可以通过在web.config中添加以下部分来解决此问题。
<connectionStrings>
<add name="registerationConnectionString"
connectionString="Data Source=YourServerName;
Initial Catalog=YourDatabaseName;
Persist Security Info=True;
User ID=yourUserId;
Password=yourPassword" />
</connectionStrings>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.