asp.net - System.FormatException: Input string was not in a correct format -


in following code, when try add item asp dropdownlist, system.formatexception: input string not in correct format, thrown.

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 branchtable 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"));                 (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)     {      } } 

however, when comment such lines there no exception thrown.

what problem , possible solution?

instead of

int totalsem = int32.parse(semreader["totalsem"].tostring()); 

try

int totalsem; int32.tryparse(semreader["totalsem"].tostring(),totalsem); 

and if takes care of exception addressing issues field.


Comments