将xml文件中的属性应用于表单

本文关键字:属性 应用于 表单 xml 文件 | 更新日期: 2023-09-27 17:51:04

可能重复:
C#加载XML文件

我的程序有问题。我需要读取一些xml文件,其中有Form属性,我需要在运行(加载(程序时将其应用于程序。我得到了这段代码,但在运行时它给了我一个错误(对象引用未设置为对象实例(。我现在迷失了方向,真的不知道如何将xml中的这些设置应用到我的程序中。

<Form>
   <Size>
     <Width>558</Width> 
     <Height>537</Height> 
   </Size>
   <Text>XML saving</Text> 
   <Name>Test_name</Name> 
</Form>
    public formaENA()
    {
        InitializeComponent();
    }
    private void Form1_Load(object sender, EventArgs e)
    {
        XDocument newDoc = XDocument.Load(@"C:'testXML.xml");
        var form = from size in newDoc.Descendants("Size")
                    select new
                    {
                        Width = Convert.ToInt32(size.Element("Width").Value),
                        Height = Convert.ToInt32(size.Element("Height").Value)           
                    };
        foreach(var size in form)
        {
            formaENA.ActiveForm.Width = size.Width;
            formaENA.ActiveForm.Height = size.Height;              
        }

将xml文件中的属性应用于表单

您收到这个错误是因为您还没有初始化formaENA。尝试在将任何属性附加到该表单之前创建该表单。

    formaENA frm = new formaENA();
    foreach(var size in form)
    {
        frm.Width = size.Width;
        frm.Height = size.Height;              
    }
    frm.Show();

在我看来,您似乎还没有初始化formaENA。如果它没有名为ActiveForm的静态属性,那么应该得到一个空指针异常。