2016-03-14 57 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)); 
    } 

那麼,請看看消息彈出驗證和調試的程序;