如果输入数据库中不存在的输入,如何打印出错误消息? N层

How do I print out error message if I enter an input that doesn't exist in Database? N-Tier

关于我的问题的简要说明:如果我输入的数字在我的程序的数据库中不存在,我希望我的程序打印出一条错误消息而不会导致程序崩溃。这是我的代码:

  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);
  }

第一件事:您仍在处理流程的剩余部分,即检索电影详细信息,即使 this.txtMovieID 为空。您需要停止处理并且 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 :检查 GetMovie(N) 的结果是否为空,如果为空,则中断并 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);
  }