问题
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?
回答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();
// ....
}
回答2:
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();
回答3:
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.
回答4:
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.
回答5:
primo is null because cbxValuta has no selected item.
来源:https://stackoverflow.com/questions/14356827/nullreferenceexception-was-unhandled-c-sharp