LINQ XML从另一种形式获取组合框值c#

时间:2016-09-07 10:03:53

标签: c# xml winforms linq label

我想在两个表单之间的标签中显示xml信息,但我得到“对象引用未设置为对象的实例”。我一直在寻找几个小时,但还没有解决方案。

cbFrom cbTo 是我的两个文本框,我需要将其值从一个 FORM1 发送到另一个 FORM2

public partial class FORM1 : Form
{
    public string combofrom
    {
        get { return cbFrom.Text; }
        set { cbFrom.Text = value; }
    }

    public string comboto
    {
        get { return cbTo.Text; }
        set { cbTo.Text = value; }
    }
  }

FORM2

   public partial class FORM2 : Form
{
 public FORM2()
    {
        InitializeComponent();
    }

    private FORM1 = new FORM1();

     public FORM1(FORM2 form)
    {
        this.form = form;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        XDocument xmlDoc = XDocument.Load("schedulemanager.xml");

        var n = from ep in xmlDoc.Descendants("Aircraft")
                 where ep.Attribute("mdy").Equals(form.combofrom.ToString())
                 select ep;

        label8.Text = n.FirstOrDefault().ToString();// ****Object reference     
                                      //not set to an instance of an object

    }

提前致谢!

UPDATE 最后我找到了解决方案。

FORM1

     public void FORM1(object sender, EventArgs e)
    {
    FORM2 f2 = new FORM2(this);
    }
    /**You don't need any getter or setter

FORM2

     private FORM2 f2;
     public frmScheduleResult( frmReservation f)
    {
        InitializeComponent();
        f2 = f;

    }

     var name = xmlDoc.Descendants("Aircraft")

        .Where(n => n.Attribute("Source").Value == f1.cbFrom.Text)
        .Select(n => (string)n) 
        .FirstOrDefault();      
         label7.Text = name;

2 个答案:

答案 0 :(得分:1)

试试这个,我希望它对你有所帮助:

String name = xmlDoc.Descendants("Aircraft")
              .Elements("Name")
              .Where(n => (string)n.Attribute("mdy") == form.combofrom.ToString())
              .Select(n => (string)n) // get element's value
              .FirstOrDefault();      // select only first value, if any

label8.Text = name.ToString();

答案 1 :(得分:0)

试试这个:

if(form.combofrom!=null)
{

  var n = (from ep in xmlDoc.Descendants("Aircraft")
                     where ep.Attribute("mdy").Equals(form.combofrom.ToString())
                     select ep).FirstOrDefault();

    if(n!=null)
    {
     label8.Text = n.FirstOrDefault().ToString();
    }
}