0

在以下代码中,当我尝试将项目添加到 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)
    {

    }
}

但是,当我评论所有这些行时,没有抛出异常。

可能是什么问题及其可能的解决方案?

4

1 回答 1

0

代替

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

尝试

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

如果这样可以解决异常,那么请考虑解决该领域的问题。

于 2011-04-29T20:24:47.603 回答