I am building a Windows forms application using VS2010. I want to read the value the user selected from the dropdown ComboBox and generate patientNo based on that. But when i run the application I get a NullReferenceException.
Here is my code:
private void button1_Click(object sender, EventArgs e)
{
string patientNumber;
string gender = comboBox2.SelectedValue.ToString();
if (gender != null)
{
if (gender == "Female")
{
var generator = new PatientNumberGenerator();
patientNumber = generator.GeneratePatientNumber(Gender.Female);
const string message = "patientNumber";
const string caption = "Testing PatientNumber class";
var result = MessageBox.Show(message, caption,
MessageBoxButtons.YesNo,
MessageBoxIcon.Question);
}
else if (gender == "Male")
{
var generator = new PatientNumberGenerator();
patientNumber = generator.GeneratePatientNumber(Gender.Male);
const string message = "patientNumber";
const string caption = "Testing PatientNumber class";
var result = MessageBox.Show(message, caption,
MessageBoxButtons.YesNo,
MessageBoxIcon.Question);
}
}
}
You haven’t said which line the exception is occuring on, so it’s a bit of a shot in the dark. However:
comboBox2.SelectedValuemight be null, in which case trying to callToString()on it would cause a NullReferenceException. Try:If that’s not your issue, the exception may be inside other calls in that method, such as
GeneratePatientNumber.