否则,如果语句中断



第一个if语句有效,但是当你尝试执行else语句时,它会中断:int SearchUser = Convert.ToInt32(SearchResult.SelectedRow.Cells[1].Text);

protected void SearchResult_SelectedIndexChanged(object sender, EventArgs e)
{
    // open new connection
    SqlConnection connection1 = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
    connection1.Open();
    int SearchUser = Convert.ToInt32(SearchResult.SelectedRow.Cells[1].Text);
    int Student = Convert.ToInt32(Session["UserID"]);

    if (SearchResult.SelectedRow.Cells[1].Text != null)
    {
    String PT = "INSERT into PTutors(PersonalTutorID, StudentID) values(@SearchUser, @Student)";
    SqlCommand myCommand = new SqlCommand(PT, connection1);
    myCommand.Parameters.AddWithValue("@SearchUser", SearchUser);
    myCommand.Parameters.AddWithValue("@Student", Student);
    myCommand.ExecuteNonQuery();

    Response.Write("<script type='text/javascript'>");
    Response.Write("alert('Student Assigned to Personal Tutor');");
    Response.Write("document.location.href='ViewAssignedTutors.aspx';");
    Response.Write("</script>");
    }
    else 
    { 
    int SearchAPM = Convert.ToInt32(SearchResult.SelectedRow.Cells[9].Text);
        String PT2 = "INSERT into PTutors(PersonalTutorID, StudentID) values(@SearchAPM, @Student)";
        SqlCommand myCommand = new SqlCommand(PT2, connection1);
        myCommand.Parameters.AddWithValue("@SearchAPM", SearchAPM);
        myCommand.Parameters.AddWithValue("@Student", Student);
        myCommand.ExecuteNonQuery();

        Response.Write("<script type='text/javascript'>");
        Response.Write("alert('Student Assigned to Personal Tutor');");
        Response.Write("document.location.href='ViewAssignedTutors.aspx';");
        Response.Write("</script>");
    }
}

尝试而不是简洁

  int SearchAPM = Convert.ToInt32(SearchResult.SelectedRow.Cells[9].Text);

把健谈

  int SearchAPM = 0;
  if (!int.TryParse(SearchResult.SelectedRow.Cells[9].Text, out SearchAPM)) {
    Message.Show(String.Format(""{0}" is not an integer value.", 
      SearchResult.SelectedRow.Cells[9].Text));
  }

然后,请看一下弹出的消息并调试例程;

您尝试转换的数据格式似乎不正确。如 Msdn 所述

尝试在转换上放置断点,并查看您从单元格中给出的值。另外,您是如何确定应该使用字段 9 的?您确定您没有选择错误的字段吗?

或者,您也可以将您的转换者包裹在尝试捕获中

try{
    int SearchAPM = Convert.ToInt32(SearchResult.SelectedRow.Cells[9].Text);
} catch(FormatException ex)
{
   // Do something to debug/handle
   SearchApm = -1;
   Trace.WriteLine("Oh no, {0} is not correctly formated",SearchResult.SelectedRow.Cells[9].Text);
}

或者甚至简化这种 try catch 的版本可能是 try parse,它将在内部处理错误,如果失败,则给你一个 0。

最新更新