Archive

Posts Tagged ‘appSettings’

Get AppSettings value from code behind

December 4, 2010 1 comment

When you are developing an ASP.NET web application, you sometimes may need to reuse a term or name over and over again across the application. If the term is used in some places only, there might not be a problem to change it when you need to change the term.

However, if the application that you are developing is a big application, it will be very tedious if you need to change the term value after lots of pages has been coded. So how do you solve this?

The solution is to use AppSettings which can be located in the web.config. Values that has been added into the AppSettings tag in the web.config file can be accessed across the entire application. So, any changes made to the value of the AppSettings, it will be applied across the entire application without having to change the values page by page.

Below, I’ll be showing you how to access the AppSettings values you have added into the web.config file from the code behind file. You can also access this values from class file in your application.

 

Note: I have added a Label with the ID of “Label1” in the Default.aspx file.

 

Code in web.config:

<appSettings>
        <add key="MyAppSettings" value="Some value" />
</appSettings>

Code for C#:

Label1.Text = System.Configuration.ConfigurationManager.AppSettings["MyAppSettings"].ToString();

Code for VB.NET:

Label1.Text = System.Configuration.ConfigurationManager.AppSettings("MyAppSettings").ToString()

 

The sample code above shows you how to get the value of the key “MyAppSettings” from the collection of pre defined application settings from the AppSettings tag in the web.config file. Then it displays the value out to the Label with ID “Label1”.

 

Note: Make sure that your web application has reference to System.Configuration. Otherwise, you will get errors when you compile your web application.

Get AppSettings value in ASPX page

December 4, 2010 1 comment

In my previous post, I’ve shown how to get AppSettings value from the code behind file. Here, I’ll show you how to get AppSettings value directly from the .ASPX page.

The sample below displays the value for “MyAppSettings” key stored in web.config file as the text for a label named “Label1”.

 

Code for ASPX page:

<asp:Label Text='<%$ AppSettings:MyAppSettings %>’ runat="server" ID="Label1" />

Code in web.config:

<appSettings>
        <add key="MyAppSettings" value="Some value" />
</appSettings>

Categories: ASP.NET Tags: , ,