System.FormatException:输入字符串的格式不正确

时间:2011-04-29 20:14:55

标签: asp.net exception drop-down-menu add formatexception

在下面的代码中,当我尝试将一个Item添加到ASP DropDownList时,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 个答案:

答案 0 :(得分:0)

而不是

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

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

如果它负责处理异常,那么请研究解决该字段的问题。