The last MessageBox
with the error message doesn't work; the program just crashes. I want to use the MessageBox
to show the user that they forgot to select one of the items: Mountenbike, Rennrad, or Faltrad.
if (typen.SelectedItem.ToString() == "Mountenbike")
{
mb = new Mountenbike(artikelNr, name, ekPreis, vkPreis);
mbCounter++;
MessageBox.Show("Fertig");
}
else if (typen.SelectedItem.ToString() == "Rennrad")
{
rr = new Rennrad(artikelNr, name, ekPreis, vkPreis);
rrCounter++;
MessageBox.Show("Fertig");
}
else if (typen.SelectedItem.ToString() == "Faltrad")
{
fr = new Faltrad(artikelNr, name, ekPreis, vkPreis);
frCounter++;
MessageBox.Show("Fertig");
}
else if (typen.SelectedItem == null)
{
MessageBox.Show("Error - Please enter xyz");
}
You are probably getting an exception because you can't instantiate the method ToString()
on a null reference, assuming by your last else if
statement that the value of typen.SelectedItem
can potentially be null if nothing is selected.
You should check whether the value of typen.SelectedItem
is null
first before instantiating any methods against it. That can be done simply as:
if (typen.SelectedItem == null)
{
MessageBox.Show("Error - Please enter xyz");
return;
}
if (typen.SelectedItem.ToString() == "Mountenbike")
{
mb = new Mountenbike(artikelNr, name, ekPreis, vkPreis);
mbCounter++;
MessageBox.Show("Fertig");
}
else if (typen.SelectedItem.ToString() == "Rennrad")
{
rr = new Rennrad(artikelNr, name, ekPreis, vkPreis);
rrCounter++;
MessageBox.Show("Fertig");
}
else if (typen.SelectedItem.ToString() == "Faltrad")
{
fr = new Faltrad(artikelNr, name, ekPreis, vkPreis);
frCounter++;
MessageBox.Show("Fertig");
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.