NullReferenceException was unhandled C# [duplicate]

馋奶兔 提交于 2020-01-06 08:07:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!