Tell me more ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I'm making a simple Contact Manager as a practice project based on a XML file everything is working just fine except for two problems

Every time I click on the white blank space on ListBox, I get this exception:

Object reference not set to an instance of an object.

It doesn't happen if an item is selected on the ListBox though.

Code:

private void lstbox1_SelectedIndexChanged(object sender, EventArgs e)
{
    btnDelete.Enabled = true;

    if (rBtn1.Checked)
    {
        string xpath = "/Contacts/Contact[FullName='" + lstbox1.Text + "']";
        XmlNode node = doc.SelectSingleNode(xpath);

        txt2.Text = node["FullName"].InnerText; //This is where i get the exception
        txt3.Text = node["HomePhone1"].InnerText;
        txt4.Text = node["HomePhone2"].InnerText;
        txt5.Text = node["MobilePhone1"].InnerText;
        txt6.Text = node["MobilePhone2"].InnerText;
        txt7.Text = node["HomeAddress"].InnerText;
        txt8.Text = node["E-MailAddress"].InnerText;
    }

}

Also if someone can tell me how to search in a XML file through a TextBox that would be great. I tried Google but not much results about that.

Screenshot:

screenshot

share|improve this question
I would also recommend to ensure that you trim your input, and make sure that case of your search string matches – Roma Apr 27 at 2:45

closed as off topic by unholysampler, Jesse C. Slicer, MichaelT, Rein Henrichs, delnan Apr 27 at 8:36

Questions on Programmers Stack Exchange are expected to relate to software development within the scope defined in the FAQ. Consider editing the question or leaving comments for improvement if you believe the question can be reworded to fit within the scope. Read more about closed questions here.

1 Answer

I bet node is null because your xpath query isn't returning any results.

Adding a null reference check should take care of your problem.

private void lstbox1_SelectedIndexChanged(object sender, EventArgs e)
{
    btnDelete.Enabled = true;

    if (rBtn1.Checked)
    {
        string xpath = "/Contacts/Contact[FullName='" + lstbox1.Text + "']";
        XmlNode node = doc.SelectSingleNode(xpath);

        if( node != null ) 
        {
           txt2.Text = node["FullName"].InnerText; //This is where i get the exception
           txt3.Text = node["HomePhone1"].InnerText;
           txt4.Text = node["HomePhone2"].InnerText;
           txt5.Text = node["MobilePhone1"].InnerText;
           txt6.Text = node["MobilePhone2"].InnerText;
           txt7.Text = node["HomeAddress"].InnerText;
           txt8.Text = node["E-MailAddress"].InnerText;
        }
    }
}
share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.