0

Visual Studio 2010 - (Windows Forms) in C#

I have this code:

private void cbxValuta_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            string primo = cbxValuta.SelectedItem.ToString();
            string secondo = cbxValuta2.SelectedItem.ToString();
            double cambio = double.Parse(CurrencyConverter.Convert(1.0m, primo, secondo));
            tbxConvertito.Text = (double.Parse(tbxDaConvertire.Text) * cambio).ToString();

I get this error:

NullReferenceException was unhandled Object reference not set to an instance of an object.

How Can I solve this issue?

John Saunders
  • 157,405
  • 24
  • 229
  • 388
Vincenzo Lo Palo
  • 1,253
  • 5
  • 19
  • 32
  • At which string this exception occuring? I think __cbxValuta__ are comboboxes, so you can get __NullReferenceException__ when you take "__SelectedItem__" property value if combobox has no selected item. – acrilige Jan 16 '13 at 11:02
  • string secondo = cbxValuta2.SelectedItem.ToString(); – Vincenzo Lo Palo Jan 16 '13 at 11:03
  • If you are sure that this is where your error comes from then check the values of the selected items that they are not null before you use them. – japesu Jan 16 '13 at 11:06
  • Almost all cases of `NullReferenceException` are the same. Please see "[What is a NullReferenceException in .NET?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net)" for some hints. – John Saunders May 15 '14 at 19:08

5 Answers5

1

You probably don't have a SelectedItem i the combobox.

The object that is the currently selected item or null if there is no currently selected item.

Then these lines can fail at ToString():

string primo = cbxValuta.SelectedItem.ToString();
string secondo = cbxValuta2.SelectedItem.ToString();
Tim Schmelter
  • 411,418
  • 61
  • 614
  • 859
1

SelectedItem return null if no item was selected in a UI element. Try to add check if items has been selected

if(cbxValuta.SelectedItem != null && cbxValuta2.SelectedItem != null)
{
       string primo = cbxValuta.SelectedItem.ToString();
       string secondo = cbxValuta2.SelectedItem.ToString();
//       ....
}
Ilya Ivanov
  • 22,043
  • 4
  • 58
  • 86
1

You wrote that exception occurs at this string:

string secondo = cbxValuta2.SelectedItem.ToString();

It means or cbxValuta2 is null, or cbxValuta2.Selected item is null. Check that you select something in this combobox.

acrilige
  • 2,296
  • 16
  • 28
0

This means that either cbxValuta2 or (more likely) cbxValuta2.SelectedItem is null. This isn't strange - if you have a list in which the user can select zero items, a null is a very likely value.

You should check for it with an if before calling any method (ToString(), in this case) on it.

Theodoros Chatzigiannakis
  • 26,988
  • 8
  • 61
  • 97
0

primo is null because cbxValuta has no selected item.

CodeSpread
  • 317
  • 2
  • 5