How to Access AppSettings in Code Behind File

Category > ASP.NET || Published on : Friday, February 19, 2016 || Views: 9699 || Access AppSettings in Code Behind File


Introduction

Here Pawan Kumar will explain how to Access AppSettings in Code Behind File

Description

In previous post I have explained jQuery Datepicker Calendar With Slide Down Effect In Asp.Net, jQuery Code To Select Multiple Item By Pressing Ctrl Button In Asp.Net, How to bind dropdown list with XML file in asp.net?, Validate ASP.Net form using CSS in C#, API Demonstration ASP.NET, Age Calculator using ASP.NET & C#, and many more articles.

Now I will explain How to How to Access AppSettings in Code Behind File

So follow the steps to learn How to Access AppSettings in Code Behind File

Step 1: Change the web config file as below:-

<?xml version="1.0"?>

<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->

<configuration>

  <system.web>
    <compilation debug="false" targetFramework="4.0" />
  </system.web>
  <appSettings>
    <add key="code" value="123456" />
  </appSettings>
</configuration>

Step 2: Use the below code to retreive the web config appsetting values:-

ASPX Code:-

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2>
            How to Access AppSettings in Code Behind File</h2>
        <asp:Label ID="lblCode" runat="server" Text="Label"></asp:Label>
    </div>
    </form>
</body>
</html>

Code Behind Codes:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Configuration;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string Code = WebConfigurationManager.AppSettings["code"];
        lblCode.Text = Code;
    }
}

Screen Output:-

Conclusion:

So, In this tutorial we have learned, How to Access AppSettings in Code Behind File

Download Source Codes