2016-03-14 44 views
0

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

什么是异常消息?你说它打破了,但不是错误是什么?我要猜测 - SearchResult.SelectedRow.Cells [9] .Text'是否包含可以变成整数的值? – user1666620

+0

错误消息是:mscorlib.dll中发生类型'System.FormatException'的异常,但未在用户代码中处理 附加信息:输入字符串格式不正确。 –

+0

你试图变成一个整数的文本字段的值是什么? – user1666620

回答

0

看来你正试图转换的数据是不是在正确的格式。如在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 parse将内部处理错误,给你一个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)); 
    } 

那么,请看看消息弹出验证和调试的程序;