HTML对象引用未设置为对象的实例

时间:2011-11-27 21:20:43

标签: c# .net html visual-studio-2008 nullreferenceexception

我有一个简单的网页。内容:

<%@ Page Language="C#" 
         AutoEventWireup="true" 
         CodeFile="default.aspx.cs" 
         Inherits="_Default" %>

<!DOCTYPE HTML PUBLIC 
          "-//W3C//DTD HTML 4.01//EN" 
          "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
  <meta http-equiv="Content-type" 
        content="text/html; charset=utf-8" />
  <title>Test Page</title>
</head>
<body>
  <form id="form1" 
        runat="server">
    <div id="header" >
      <asp:Button
           ID="previous_BUT"
           runat="server"
           Height="25px"
           Text="Previous" 
           Visible="false"
           Width="100px" />
      <asp:Label
           ID="txtNewsItem"
           runat="server"
           Height="20px"  
           Visible="false"
           Width="550px" />
      <asp:Button
           ID="next_BUT"
           runat="server"
           Height="25px"
           Text="Next" 
           Visible="false"
           Width="100px" />
    </div>

  </form>
</body>
</html>

页面后面的代码(不包括Session变量和Web.config值检索)是

using ...

// **************************************************** class _Default

public partial class _Default : Page
    {

    DataTable   news_items = null;

    // ********************************************* Connection_String

    /// <summary>
    /// get the value of the database connection string from 
    /// the Web.Config file ConnectionString element
    /// </summary>
    public string Connection_String ...

    // ********************************************* Current_News_Item

    /// <summary>
    /// set or get the value of the Current_News_Item Session
    /// variable
    /// </summary>
    private int Current_News_Item ...

    // ********************************************* Number_News_Items

    /// <summary>
    /// set or get the value of the Number_News_Items Session 
    /// variable
    /// </summary>
    private int Number_News_Items ...

    // ************************************************ get_news_items

    /// <summary>
    /// retrieve the news items from the database
    /// </summary>
    /// <returns></returns>
    private DataTable get_news_items ( )
        {
        DataTable       data_table = null;
        SqlConnection   SQL_connection = null;

        try
            {
            DataSet         data_set = new DataSet ( );
            DateTime        now = DateTime.Now;
            StringBuilder   select_statement;
            SqlDataAdapter  SQL_data_adapter;
            DateTime        today;

            today = new DateTime ( now.Year, now.Month, now.Day );

            select_statement = new StringBuilder ( ).AppendFormat (
                "SELECT hpn.description " +
                "FROM tbl_homePageNews hpn " +
                "WHERE effectiveDate <= GETDATE() and status = 1 " +
                "ORDER BY sortOrder ASC",
                today.ToShortDateString ( ) );

            SQL_connection = new SqlConnection ( Connection_String );
            SQL_connection.Open ( );

            SQL_data_adapter = new SqlDataAdapter ( 
                                       select_statement.ToString ( ),
                                       SQL_connection );
            SQL_data_adapter.Fill ( data_set, "tbl_homePageNews" );

            data_table = data_set.Tables [ "tbl_homePageNews" ].
                                  Copy ( );
            }
        catch
            {
            data_table = null;
            }
        finally
            {
            if ( SQL_connection != null )
                {
                SQL_connection.Close ( );
                }
            }

        return ( data_table );
        }

    // ***************************************************** Page_Load

    protected void Page_Load ( object sender, EventArgs e )
        {

        next_BUT.Click += new EventHandler( next_BUT_Click );
        previous_BUT.Click += new EventHandler( previous_BUT_Click );

        Current_News_Item = 0;
        Number_News_Items = 0;

        if ( !Page.IsPostBack )
            {
            news_items = get_news_items ( );

            if ( news_items != null )
                {
                Number_News_Items = news_items.Rows.Count;

                previous_BUT.Visible = false;
                txtNewsItem.Visible = false;
                next_BUT.Visible = false;

                if ( Number_News_Items > 0 )
                    {
                    txtNewsItem.Visible = true;
                    txtNewsItem.Text = 
                        "  " + 
                        news_items.Rows [ Current_News_Item ] 
                                        [ "description" ].
                                   ToString ( );

                    if ( Number_News_Items > 1 )
                        {
                        previous_BUT.Visible = true;
                        next_BUT.Visible = true;
                        }
                    }
                }
            }
        }

    // ******************************************** previous_BUT_Click

    /// <summary>
    /// handle the Previous button click
    /// </summary>
    public void previous_BUT_Click ( Object sender,
                                     EventArgs e )
        {

        Current_News_Item--;
        if ( Current_News_Item < 0 )
            {
            Current_News_Item = Number_News_Items - 1;
            }

        txtNewsItem.Text =  
            "  " + news_items.Rows [ Current_News_Item ] 
                                   [ "description" ].ToString ( );
        }

    // ************************************************ next_BUT_Click

    /// <summary>
    /// handle the Next button click
    /// </summary>
    public void next_BUT_Click ( Object    sender,
                                 EventArgs e )
        {

        Current_News_Item++;
        if ( Current_News_Item >= Number_News_Items )
            {
            Current_News_Item = 0;
            }

        txtNewsItem.Text = 
            "  " + news_items.Rows [ Current_News_Item ] 
                                   [ "description" ].ToString ( );
        }

    } // class _Default

在后面的代码中,在Page_Load中是语句

                    txtNewsItem.Visible = true;
                    txtNewsItem.Text = 
                        "  " + 
                        news_items.Rows [ Current_News_Item ] 
                                        [ "description" ].
                                   ToString ( );

两者都按预期执行 - 显示第一个新闻项目。用户可以点击“上一步”按钮或“下一步”按钮来移动新闻项目。但问题出现了。以下代码是糟糕的地方

    // ************************************************ next_BUT_Click

    /// <summary>
    /// handle the Next button click
    /// </summary>
    public void next_BUT_Click ( Object    sender,
                                 EventArgs e )
        {

        Current_News_Item++;
        if ( Current_News_Item >= Number_News_Items )
            {
            Current_News_Item = 0;
            }

        txtNewsItem.Text = 
            "  " + news_items.Rows [ Current_News_Item ] 
                                   [ "description" ].ToString ( );
        }

声明

        txtNewsItem.Text = 
            "  " + news_items.Rows [ Current_News_Item ] 
                                   [ "description" ].ToString ( );

导致错误,txtNewsItem为红色。 previous_BUT_Click中发生了同样的错误。

因为在Page_Load中使用了相同的语句,所以我无法理解错误的原因。

3 个答案:

答案 0 :(得分:2)

填充news_items集合的代码可能仅在初始Page_Load调用时执行(即Page.IsPostBack == false时)?

答案 1 :(得分:2)

根据您发布的代码,我们可以看到

 news_items = get_news_items ( );

仅在第一次加载页面时调用。

将此行添加到您的活动中,它会起作用。


我认为问题出在news_items上。请将您声明的代码和页面加载的完整代码发布。你在使用if (!isPostBack)吗?

我相信你在if (!IsPostBack)你正在加载new_items表。

答案 2 :(得分:0)

检查onLoad中的news_items.Rows[Current_News_Item + 1]["description"].ToString();是否会导致相同的异常 - 如果是,则除了默认值之外的其他项尚未初始化,或者其描述尚未初始化。