ASP.NETのアプリケーション変数を利用するコードを紹介します。
UI
下図のUIを作成します。
default.aspx
テキストボックスとボタンを1つずつ配置します。
XMLファイル
<%@ Page Language="C#" AutoEventWireup="true"
CodeBehind="default.aspx.cs" Inherits="ApplicationVariable._default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</div>
</form>
</body>
</html>
result.aspx
XMLファイル
<%@ Page Language="C#" AutoEventWireup="true"
CodeBehind="result.aspx.cs" Inherits="ApplicationVariable.result" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
</form>
</body>
</html>
コード
以下のコードを記述します。
default.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace ApplicationVariable
{
public partial class _default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Application["data"] = TextBox1.Text;
Response.Redirect("result.aspx");
}
}
}
解説
Button1_Click
Application["data"] = TextBox1.Text;
にてキー名"data"のアプリケーション変数にテキストボックスの値を設定します。
Response.Redirect("result.aspx");
にて"result.aspx"ページにリダイレクトします。(ページ遷移)
result.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace ApplicationVariable
{
public partial class result : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = (string)Application["data"];
}
}
}
解説
Loadイベント
Label1.Text = (string)Application["data"];
キー名"data"のアプリケーション変数を読み取り値をLabel1に表示します。
実行結果
プロジェクトを実行します。下図の画面が表示されます。
テキストボックスに値を入力します。今回は"しろくま"と入力しました。入力後ボタンをクリックします。
"result.aspx"ページに切り替わりテキストボックスに入力した文字が画面に表示されます。
注意
アプリケーション変数はアプリケーションで共通のため、ユーザーごとやセッションごとに値を保持することができません。べつのWebブラウザで直接"result.axpx"ページを表示すると先に設定された"しろくま"の文字が画面に表示されます。
著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2021-01-19
作成日: 2013-05-30