2011-04-29 23 views
0

在下面的代碼中,當我嘗試向ASP DropDownList添加一個Item時,System.FormatException:輸入字符串的格式不正確。System.FormatException:輸入字符串格式不正確

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.Data.SqlClient; 

public partial class ScheduleExam : System.Web.UI.Page 
{ 
    protected void Page_Load(object sender, EventArgs e) 
    { 
     String connection = System.Configuration.ConfigurationManager.ConnectionStrings["TYCConnection"].ConnectionString; 

     String branch = Request.Form["ctl00$ctl00$MainContent$AdminMainContent$BranchDropDownList"]; 
     if (!String.IsNullOrWhiteSpace(branch)) 
     { 
      if (!branch.Equals("00")) 
      { 
       SqlConnection sqlConn = new SqlConnection(connection); 
       String semQuery = "select totalSem from branchTable where branchId='" + branch + "'"; 
       SqlCommand semCommand = new SqlCommand(semQuery, sqlConn); 

       sqlConn.Open(); 
       SqlDataReader semReader = semCommand.ExecuteReader(); 
       semReader.Read(); 
       int totalSem = Int32.Parse(semReader["totalSem"].ToString()); 
       SemesterDropDownList.Items.Clear(); 
       SemesterDropDownList.Enabled = true; 
       //ListItem list = new ListItem("Select"); 
       SemesterDropDownList.Items.Add(new ListItem("select")); 
       for (int sem = 1; sem <= totalSem; sem++) 
       { 
        //SemesterDropDownList.Items.Add(sem.ToString()); 
       } 
       sqlConn.Close(); 
      } 
      else 
      { 
       SemesterDropDownList.Items.Clear(); 
       SemesterDropDownList.Enabled = false; 
       //SemesterDropDownList.Items.Add("First Select Branch"); 
      } 
     } 
     else 
     { 
      SemesterDropDownList.Enabled = false; 
      //SemesterDropDownList.Items.Add("First Select Branch"); 
     } 
    } 
    protected void RegisterButton_Click(object sender, EventArgs e) 
    { 

    } 
} 

但是,當我評論所有這些行時,不會拋出異常。

可能是什麼問題及其可能的解決方案?

+1

首先使用調試器遍歷代碼。在哪一點你會得到錯誤? – NotMe 2011-04-29 20:17:56

回答

0

而不是

int totalSem = Int32.Parse(semReader["totalSem"].ToString()); 

嘗試

int totalSem; 
Int32.TryParse(semReader["totalSem"].ToString(),totalSem); 

,如果這發生異常的護理,然後考慮解決與該領域的問題。