将返回值分配给标签控件时出现NullReferenceException

时间:2014-05-12 12:53:36

标签: c# asp.net nullreferenceexception

此刻我有点难过。我在我的网络应用程序上有两个标签控件正试图分配一些文本值,第一个标签工作正常,而第二个标签没有。在母版页Load事件期间引用控件,请参阅下面的代码

protected void Page_Load(object sender, EventArgs e)
{
    string id = Convert.ToString(Session["id"]);
    //string rtn = Convert.ToString(GetRequestsCount(id));
    //StringBuilder rtn = new StringBuilder();
    //rtn.Append(id);
    int display = GetRequestsCount(id);

    if (!this.IsPostBack) //prevent post back
    {
        if (string.IsNullOrEmpty(Session["id"].ToString()))
        {
            Response.Redirect("welcome.aspx", true);
        }
        else
        {
            lblUser.Text = Session["FName"].ToString() + " " + Convert.ToString(Session["LName"]) + " {" + id + "}";
            Label1.Text = string.Concat(Convert.ToString(display), " New Request(s)");
        }

public int GetRequestsCount(string id)
{
    string query = "SELECT count(*) FROM TableWHERE username='" + id + "' AND (isActive ='False')";
    int count = 0;

    try
    {
        using (SqlConnection thisConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString))
        {
            using (SqlCommand cmdCount = new SqlCommand(query, thisConnection))
            {
                thisConnection.Open();
                count = (int)cmdCount.ExecuteScalar();
            }
        }
        return count;
    }
    catch (NullReferenceException ex)
    {

        throw;
    }
}

2 个答案:

答案 0 :(得分:0)

我最好的猜测,没有行号,这就是问题......

ConfigurationManager.ConnectionStrings [“con”]。ConnectionString

检查Web.config中是否确实有一个具有此名称的连接字符串

答案 1 :(得分:0)

如果在尝试访问Label1时抛出NullReferenceException,则需要在尝试更改其Text值之前检查Label控件是否存在

if (Label1 != null)
{
    Label1.Text = string.Concat(Convert.ToString(display), " New Request(s)");
}

或者您需要在代码中明确声明标签:

Label lblRequests = (Label) <container holding Label>.FindControl("Label1");