ViewStateに独自の値を保存するコードを紹介します。
概要
ViewStateに値を保存する場合はPageのViewStateプロパティに値を保存します。
ViewState["(キー名)"]
に値を代入することで保存できます。
UI
ASP.NET Webアプリケーションを新規作成します。Webフォームを作成し下図のUIを準備します。Label, Buttonを1つずつ配置します。
default.aspx
<%@ Page Language="C#" AutoEventWireup="true"
CodeBehind="default.aspx.cs" Inherits="SimpleViewState._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:Label ID="Label1" runat="server" Text="Label"></asp:Label><br />
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" /><br />
</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 SimpleViewState
{
public partial class _default : System.Web.UI.Page
{
List<string> StrList;
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = "";
if (ViewState["Data"] != null) {
StrList = (List<string>)ViewState["Data"];
}
else {
StrListCreateData();
ViewState["Data"] = StrList;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
for (int i=0 ; i< StrList.Count; i++){
Label1.Text += StrList[i] + ", ";
}
}
private void StrListCreateData()
{
StrList = new List<string>();
StrList.Add("Penguin");
StrList.Add("Duck");
StrList.Add("Camel");
StrList.Add("Whale");
}
}
}
解説
ページのLoadイベントではラベルの初期化とViewStateからの値の取り出しをします。ViewStateの"Data"キーに値がない場合は
StrListCreateData()メソッドを呼び出しList<string>クラスのデータを作成します。作成したデータをViewState["Data"]に代入します。"Data"はViewStateのデータにアクセスするためのキーになります。
ViewStateの"Data"キーに値がある場合はデータの取り出しをします。データはキャストしてList<string>オブジェクトとして取得します。
Page_Load
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = "";
if (ViewState["Data"] != null) {
StrList = (List<string>)ViewState["Data"];
}
else {
StrListCreateData();
ViewState["Data"] = StrList;
}
}
Button1_Click
protected void Button1_Click(object sender, EventArgs e)
{
for (int i=0 ; i< StrList.Count; i++){
Label1.Text += StrList[i] + ", ";
}
}
ボタンのクリックイベントではStrListの要素を一つずつカンマで区切りLabelに表示します。
実行結果
プロジェクトを実行します。下図の画面が表示されます。
ボタンをクリックします。List<string>オブジェクトに追加したデータの内容がラベルに表示されます。
著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2024-01-06
作成日: 2013-05-29