2011-04-29 60 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); 

,如果这发生异常的护理,然后考虑解决与该领域的问题。

相关问题