System.FormatException: входная строка была в неправильном формате - PullRequest
0 голосов
/ 30 апреля 2011

В следующем коде, когда я пытаюсь добавить элемент в 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 голосов
/ 30 апреля 2011

вместо

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

попробовать

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

и, если это устранит исключение, посмотрите на решение проблем с этим полем.

...