G Gr
G Gr

Reputation: 6080

object reference not set to an instance of an object xdocument

Hi I get an error on the line commented in the below code object reference not set to an instance of an object is there a way to fix it?

    private void button20_Click(object sender, EventArgs e)
    {
        string blabla1 = string.Format("http://localhost:8000/Service/AuthenticateUser/{0}/{1}", textBox30.Text, textBox31.Text);
        XDocument xDoc = XDocument.Load(blabla1);
        xDoc.Element("StudentID").Value.ToList(); // object reference not set to an instance of an object?


        dataGridView12.DataSource = xDoc;
    }

Upvotes: 0

Views: 2047

Answers (1)

Henk Holterman
Henk Holterman

Reputation: 273179

When xDoc.Element("StudentID") is not found, calling .Value will give that exception.

You probably want

 //xDoc.Element("StudentID").Value.ToList();
 //List<string> ids = xDoc.Descendants("StudentID").Value.ToList();
 List<string> ids = xDoc.Descendants("StudentID").Select(e => e.Value).ToList();

But that assumes the XML does not use namespaces.

Edit:

im trying to return result.StudentID;

string id = xDoc.Descendants("StudentID").Single().Value;

Upvotes: 2

Related Questions