Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null Reference Exception

Tags:

c#

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

like image 732
Rookie Avatar asked Jan 21 '26 01:01

Rookie


2 Answers

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

like image 127
Joel Goodwin Avatar answered Jan 23 '26 14:01

Joel Goodwin


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.

like image 39
Ikke Avatar answered Jan 23 '26 15:01

Ikke



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!