A quick brief explanation on my question: I want to my program to print out an error message without crashing the program if I enter a number that doesn't exist in my program's Database. Here is my code:
listBox1.Items.Clear();
BusinessTier.Business BT = new BusinessTier.Business("netflix.mdf");
if (this.txtMovieID == null) //Hoping this would work and return to the program if I enter a wrong input.
{
listBox1.Items.Add("**Error, this movie ID doesn't exist, or database is empty?!");
}
int N = System.Convert.ToInt32(this.txtMovieID.Text);
BusinessTier.Movie movie = BT.GetMovie(N);
BusinessTier.MovieDetail movieid = BT.GetMovieDetail(movie.MovieID); //this part will crash the program if I type a number like 0 or greater than 250 when my database contained 250 rows.
//display results:
listBox1.Items.Add(movie.MovieName);
foreach (BusinessTier.Review r in movieid.Reviews)
{
listBox1.Items.Add(r.UserID + ": " + r.Rating);
}
First thing : you are still processing the remaining part of the process, i.e retrieving the Movie Details, even if this.txtMovieID
is null. You need to stop the processing and return
listBox1.Items.Clear();
BusinessTier.Business BT = new BusinessTier.Business("netflix.mdf");
if (this.txtMovieID == null) //Hoping this would work and return to the program if I enter a wrong input.
{
listBox1.Items.Add("**Error, this movie ID doesn't exist, or database is empty?!");
return; // exit out if the MovieID is null
}
Second : put a check to see whether the result of GetMovie(N)
is null or not and if it is null, break and return
int N = System.Convert.ToInt32(this.txtMovieID.Text);
BusinessTier.Movie movie = BT.GetMovie(N);
if (movie == null) return; // exit if the GetMovie result is null
BusinessTier.MovieDetail movieid = BT.GetMovieDetail(movie.MovieID); //this part will crash the program if I type a number like 0 or greater than 250 when my database contained 250 rows.
//display results:
listBox1.Items.Add(movie.MovieName);
foreach (BusinessTier.Review r in movieid.Reviews)
{
listBox1.Items.Add(r.UserID + ": " + r.Rating);
}