NullReferenceException but checking for Null?
I click a button on my .NET MAUI UI to Create a new course. ContentPage loads, I enter my information. If I leave any of the entry fields blank, the program crashes... stating
System.NullReferenceException Message=Object reference not set to an instance of an object.System.NullReferenceException Message=Object reference not set to an instance of an object.private async void SaveCourseButton_Clicked(object sender, EventArgs e)
{
Course course = new Course(id, CourseName.Text, StartDate.Date, EndDate.Date, StatusPicker.SelectedIndex, InstructorName.Text, InstructorPhone.Text, InstructorEmail.Text, CourseNotes.Text, 0, 0);
var result = DataObjects.ValidateCourseInfo(activeTerm, course);
if (result.Length == 0)
{
SQLFunctions.AddNewCourse(course);
await Navigation.PopAsync();
}
else
{
await DisplayAlert("ERROR", result, "OK");
}
}
public static string ValidateCourseInfo(Term term, Course course)
{
if (course.CourseName.Length == 0 || course.CourseName is null)
{
return "Course must have a name.";
}
else if (course.EndDate.Date < course.StartDate.Date)
{
return "End date must be equal or greater than start date.";
}
else if (course.StartDate.Date < term.StartDate || course.StartDate.Date > term.EndDate || course.EndDate.Date < term.StartDate || course.EndDate.Date > term.EndDate)
{
return "Course start and end dates must fall within term start and end dates.";
}
else if (course.Status == -1)
{
return "Must pick a course status.";
}
else if (course.InstructorName.Length == 0 || course.InstructorName is null)
{
return "Instructor must have a name.";
}
...
else
{
return string.Empty;
}
}private async void SaveCourseButton_Clicked(object sender, EventArgs e)
{
Course course = new Course(id, CourseName.Text, StartDate.Date, EndDate.Date, StatusPicker.SelectedIndex, InstructorName.Text, InstructorPhone.Text, InstructorEmail.Text, CourseNotes.Text, 0, 0);
var result = DataObjects.ValidateCourseInfo(activeTerm, course);
if (result.Length == 0)
{
SQLFunctions.AddNewCourse(course);
await Navigation.PopAsync();
}
else
{
await DisplayAlert("ERROR", result, "OK");
}
}
public static string ValidateCourseInfo(Term term, Course course)
{
if (course.CourseName.Length == 0 || course.CourseName is null)
{
return "Course must have a name.";
}
else if (course.EndDate.Date < course.StartDate.Date)
{
return "End date must be equal or greater than start date.";
}
else if (course.StartDate.Date < term.StartDate || course.StartDate.Date > term.EndDate || course.EndDate.Date < term.StartDate || course.EndDate.Date > term.EndDate)
{
return "Course start and end dates must fall within term start and end dates.";
}
else if (course.Status == -1)
{
return "Must pick a course status.";
}
else if (course.InstructorName.Length == 0 || course.InstructorName is null)
{
return "Instructor must have a name.";
}
...
else
{
return string.Empty;
}
}