Rookie
Rookie

Reputation: 113

Null Reference Exception

in c sharp win-forms

i have added a combo box control to my form and added items accordingly into the combo box m trying to the item on select-index is assigned to a string which is passed as parameter to function declared in the following manner:

private void cmbPayment_SelectedIndexChanged(object sender, EventArgs e)
    {
        string pm = cmbLocation.SelectedItem.ToString();
        payment(pm);
    }

THE FUNCTION:

public void payment(string pym)
    {
        jd.PaymentMode = pym;

    }

alt text http://img42.imageshack.us/img42/8691/adssd.png

Upvotes: 3

Views: 754

Answers (5)

James Bloomer
James Bloomer

Reputation: 5322

As others have suggested it looks like you are looking at the SelectedItem on the wrong control.

It's worth thinking about how you could have worked this out: When debugging you should be able to see what is null, presumably SelectedItem? It's also worth noting that you can look at the sender object, which is the control that raised the event. In the debugger you can look at and compare the selections, seeing cmbLocation compared to the sender may have jogged the realisation.

Upvotes: 0

plenderj
plenderj

Reputation: 573

You're calling a method (ToString()) on the SelectedItem property of cmbLocation. If SelectedItem is null/Nothing (or cmbLocation is null/Nothing) then you would get a NullReferenceException

Upvotes: 0

Ikke
Ikke

Reputation: 101251

It looks like there is no item selected on cmbLocation. If there is no item selected, the SelectedItem property will be null, and you can't call toString on null.

Do you mean cmbLocation or cmbPayment? Because this happens in a cmbPayment event.

One sollution would be to check for null:

private void cmbPayment_SelectedIndexChanged(object sender, EventArgs e)
{
    if(!cmbPayment.SelectedItem == null)
    {
        string pm = cmbLocation.SelectedItem.ToString();
        payment(pm);
    }
}

This is good practice anyway to prevent NullPointerExceptions.

Upvotes: 2

Joel Goodwin
Joel Goodwin

Reputation: 5086

Looks to me like "cmbLocation" should be "cmbPayment" ?

Upvotes: 7

user47322
user47322

Reputation:

This occurs when nothing is selected.

However, as the others have suggested, it looks like you're referring to the wrong combo box, so even though cmdPayment may have a selected item, you're not referring to it. You've written cmbLocation

Upvotes: 1

Related Questions