Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert System.Web.Configuration.WebConfigurationManager.AppSettings from String to INT

Tags:

c#

asp.net-mvc

I have defined the following inside my web.config file:-

<add key="TechPageSize" value="20" />

But I m unable to reference this value inside my paging parameters as follow:-

var servers = repository.AllFindServers(withOutSpace).OrderBy(a => a.Technology.Tag).ToPagedList(page, (Int32)System.Web.Configuration.WebConfigurationManager.AppSettings["TechPageSize"]);

and I will get an error that it can not change String to INT.

Any idea what is the problem ?

like image 572
john Gu Avatar asked Nov 18 '13 11:11

john Gu


2 Answers

int techPageSize;
if (!int.TryParse(ConfigurationManager.AppSettings["TechPageSize"], out techPageSize))
{
    throw new InvalidOperationException("Invalid TechPageSize in web.config");
}

Int32.TryParse has two effects:

  • It converts the app setting to an integer and stores the result in techPageSize, if possible.
  • If the value cannot be converted, the method returns False, allowing you to handle the error as you see fit.

PS: It suffices to use ConfigurationManager.AppSettings, once you have imported the System.Configuration namespace.

like image 143
Heinzi Avatar answered Oct 24 '22 20:10

Heinzi


The result of

System.Web.Configuration.WebConfigurationManager.AppSettings["TechPageSize"]

is a string, you can't just cast a string to int. Use Convert.ToInt32 or int.TryParse to get the integer value of the string.

int pagesize = Convert.ToInt32(System.Web.Configuration.WebConfigurationManager.AppSettings["TechPageSize"]);

or

bool succeed = int.TryParse(System.Web.Configuration.WebConfigurationManager.AppSettings["TechPageSize"], out pagesize);
like image 24
Peter Avatar answered Oct 24 '22 19:10

Peter