【问题标题】:C#: Why do I keep getting System.NullReferenceException in my code [duplicate]C#:为什么我的代码中不断出现 System.NullReferenceException [重复]
【发布时间】:2015-12-03 19:12:45
【问题描述】:

我是 Winforms 和 C# 的新手。我的表单假设读取 XML 并将其一些节点的值添加到表单文本框。它还应该通过用户插入文本框中的值来更新/修改这些节点值,然后保存它们。这是表单的样子:
Form Design

表单代码:
裸记button4_Click = '添加按钮'。 button2_Click = '修改按钮'。

using System;
using System.ComponentModel;
using System.Windows.Forms;
using System.Xml;

namespace WindowsForm
{
public partial class Form1 : Form, INotifyPropertyChanged
{
    XmlDocument doc = new XmlDocument();
    XmlElement m_textElem1;
    XmlElement m_textElem2;
    XmlElement m_textElem3;

    public string TextElement1Content
    {
        get { return m_textElem1.InnerText; }
        set { m_textElem1.InnerText = value; }
    }

    public string TextElement2Content
    {
        get { return m_textElem2.InnerText; }
        set { m_textElem2.InnerText = value; }
    }

    public string TextElement3Content
    {
        get { return m_textElem3.InnerText; }
        set { m_textElem3.InnerText = value; }
    }
    public Form1()
    {
        InitializeComponent();
    }


    private void Form1_Load(object sender, EventArgs e)
    {

    }


    private void button2_Click(object sender, EventArgs e)

    {
        doc.Load("C:\\Users\\Fahad\\Documents\\Visual studio 2015\\Projects\\ClassLibrary1\\XMLFile3.xml");
        m_textElem1 = doc.SelectSingleNode("Twittercards/Card1/title") as XmlElement;
        m_textElem2 = doc.SelectSingleNode("Twittercards/Card1/image") as XmlElement;
        m_textElem3 = doc.SelectSingleNode("Twittercards/Card1/description") as XmlElement;

        textBox1.DataBindings.Add("Text", this, "TextElement1Content");
        textBox2.DataBindings.Add("Text", this, "TextElement2Content");
        richTextBox1.DataBindings.Add("Text", this, "TextElement3Content");

    }

    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;

    }

    private void textBox1_TextChanged(object sender, EventArgs e)
    {

    }

    private void button3_Click(object sender, EventArgs e)
    {

    }

    XmlDocument xDoc = null;

    private void button4_Click(object sender, EventArgs e)
    {
          OpenFileDialog ofd = new OpenFileDialog();
          if (ofd.ShowDialog() == DialogResult.OK)
           {

            XmlElement root = xDoc.DocumentElement;
            XmlNodeList nodes = root.SelectNodes("Twittercards/Card1");
            xDoc.Load(ofd.FileName);

            foreach (XmlNode node in nodes)
            {
                var node1 = xDoc.SelectSingleNode(@"Twittercards/Card1/title");
                node1.InnerText = textBox1.Text;
                var node2 = xDoc.SelectSingleNode(@"Twittercards/Card1/image");
                node1.InnerText = textBox2.Text;
                var node3 = xDoc.SelectSingleNode(@"Twittercards/Card1/description");
                node1.InnerText = richTextBox1.Text;
                xDoc.Save(ofd.FileName);
                // textBox1.Text = xDoc.SelectSingleNode(@"Twittercards/Card1/title").InnerText;
                //  textBox2.Text = xDoc.SelectSingleNode(@"Twittercards/Card1/image").InnerText;
                //  richTextBox1.Text = xDoc.SelectSingleNode(@"Twittercards/Card1/description").InnerText;
            }
        }
    }

    private void button1_Click(object sender, EventArgs e)
    {
        doc.Save("C:\\Users\\Fahad\\Documents\\Visual studio 2015\\Projects\\ClassLibrary1\\XMLFile3.xml");
    }

    public event PropertyChangedEventHandler PropertyChanged;

    public void NotifyPropertyChanged(string propName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propName));
        }
    }

    private void textBox2_TextChanged(object sender, EventArgs e)
    {

    }

    private void richTextBox1_TextChanged(object sender, EventArgs e)
    {

    }
}

}

“添加按钮”的异常来自:XmlElement root = xDoc.DocumentElement;

“修改按钮”的异常来自:

public string TextElement1Content
{
    get { return m_textElem1.InnerText; }
    set { m_textElem1.InnerText = value; }
}

如何修复此代码以解决我最初的任务?请帮忙。谢谢

【问题讨论】:

  • button2_Click 之后的文本元素是否包含任何内容?您是否使用调试器逐步完成了此操作?
  • 您首先访问文档,然后才将数据加载到其中。自然会导致错误。此外,更好地命名您的控件,这样就无需向任何人解释 button4 是这个而 button2 是那个。
  • 还这样其他人就不必在您的代码中搜索以下XmlDocument xDoc = null; 为什么没有在您声明了其余对象的类的顶部声明..?然后你在顶部再次声明了这个`XmlDocument doc = new XmlDocument();`

标签: c# xml winforms


【解决方案1】:

您必须在使用对象之前对其进行初始化,具体取决于您何时需要使用它。要么添加某种类似这样的逻辑:

if (m_textElem1==null) {
    // initialize the object
}

或者在构造函数中:

public Form1() {
    Initialize();
   // initialize the object here
}

【讨论】:

  • 我确实初始化了构造函数,它仍然抛出异常。
【解决方案2】:

xDoc 在您的 button4_Click 方法之前的行中被声明为 null。您不能访问空对象的属性。

我认为您需要在访问 xDoc.DocumentElement 属性之前移动 xDoc.Load(ofd.FileName) 行。

xDoc.Load(ofd.FileName);    
XmlElement root = xDoc.DocumentElement;
XmlNodeList nodes = root.SelectNodes("Twittercards/Card1");

另外,您确定 xDoc 变量的范围吗?也许需要将它带入您的方法中。

【讨论】:

  • 感谢您的回答,它起作用了,它不再抛出异常,但是按钮的功能不起作用,因为 XML 文件中的节点未添加到文本框。任何想法为什么?
  • 在 button4_CLick 函数中,您一直分配给 node1,而不是分配给 node2 和 node3。如果我正确理解该功能,您将从 UI 文本框中获取项目并更新 XML,然后保存,对吗?如果是这种情况,XML 不会更新文本框,则相反。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多