ASP.NET - System.NullReferenceException:未将对象引用设置为对象的实例

时间:2016-05-27 10:58:05

标签: c# sql asp.net

我在笔记本电脑上创建了一个项目,它工作正常。

我将我的项目转移到另一台笔记本电脑,现在它给我一个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>

2 个答案:

答案 0 :(得分:0)

由于此行发生错误:

SqlConnection conn = 
    new SqlConnection(ConfigurationManager.ConnectionStrings
                                          ["registerationConnectionString"]
                                          .ConnectionString);

您应该假设ConfigurationManager.ConnectionStrings为null,并查找可能未正确复制的配置文件。当您从.ConnectionString的索引访问者处尝试.ConfigurationManager.ConnectionStrings时,它会返回null,因为您尚未在web.config中配置一个web.config。在web.config中查找connectionStrings部分。

<强>更新

由于您提供了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>

create view q2_min_ps_supplycost as
select
    p_partkey as min_p_partkey,
    min(ps_supplycost) as min_ps_supplycost
from
    part,
    partsupp,
    supplier,
    nation,
    region
where
    p_partkey = ps_partkey
    and s_suppkey = ps_suppkey
    and s_nationkey = n_nationkey
    and n_regionkey = r_regionkey
    and r_name = 'EUROPE'
group by
    p_partkey;

答案 1 :(得分:0)

您在web.config文件中没有任何连接字符串,其名称为$f = 'Saturday'; $data = 'sat,sun'; $find = strtolower(substr($f, 0,3)); $str = stristr($data , $find); if($str) echo 'found'; else echo 'not found'; ,因此registerationConnectionString为我们提供空值,然后当我们想要获得null ConfigurationManager.ConnectionStrings["registerationConnectionString"]时,给了我们ConnectionString。您可以通过在web.config中添加以下部分来解决此问题。

System.NullReferenceException