从ListBox项创建列表时出现NullReferenceException

时间:2014-01-19 14:05:19

标签: c# list windows-phone-8 windows-phone nullreferenceexception

在我的应用程序中,我遇到了一些我根本无法上班的事情。我使用此代码将文本添加到列表中,并将其保存为列表框中的每个文本框。这是我的代码:

protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
    // Save the lecture
    int amount = paragraphListBox.Items.Count();

    for (int i = 0; i < amount; i++)
    {
        // save the paragraphs, one by one

        // Get the current item
        var current = paragraphListBox.Items[i] as TextBox;
        String paragraph = current.Text.ToString();

        // Add the paragraph to the list
        paragraphList.Add(paragraph);

        try
        {
            // Try to remove a setting
            settings.Remove(lectureName + "-lecture");
        }
        catch (Exception)
        {
        }
        try
        {
            // Try to add a setting
            settings.Add(lectureName + "-lecture", paragraphList);
        }
        catch (Exception)
        {
        }
        try
        {
            // Try to save the settings
            settings.Save();
        }
        catch (Exception)
        {
        }
    }
}

行:“paragraphList.Add(paragraph);”,抛出NullReferenceException。

1 个答案:

答案 0 :(得分:2)

我忘记了一行非常重要的代码......:

        // Initialize paragraphList
        paragraphList = new List<String>();