否则,如果声明中断

时间:2016-03-14 12:24:59

标签: c# asp.net session if-statement sql-update

第一个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>");
    }
}

2 个答案:

答案 0 :(得分:1)

尝试而不是简洁

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

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

答案 1 :(得分:0)

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

所述

尝试在转换器上放置断点,并查看从单元格中提供的值。另外,您是如何确定应使用字段9的?你确定你不只是选择了错误的字段吗?

或者你也可以在try catch中加入你的转换

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。