![](/img/trans.png)
[英]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.