0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

チェックボックスの値を復元

Posted at

今回はセッションに持たせ、複数のチェックボックスを保持することを考慮しました。
if (Session["checkbox"] != null)
{
checkedStates = Session["checkbox"] as Dictionary;
}else{
checkedStates = new Dictionary();
}

既にチェックがあればセッションから取得、なければ新規で作成をする。

// クリックされたチェックボックスから行を特定する
CheckBox target = (CheckBox)sender;
GridViewRow row = (GridViewRow)target.NamingContainer;

//復元する際の主キーを取得する
string ID = grdList.DataKeys[row.RowIndex].Value.ToString();

// 行番号を取得
int rowIndex = row.RowIndex;

// チェックボックスの状態取得
bool isChecked = target.Checked;

// キーを指定しチェックボックスの状態を保持
checkedStates[ID] = isChecked;

// 取得した情報をセッションに保存
Session["checkbox"] = checkedStates;

ーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーー
再バインド時
grdOwnedShipList.DataSource = DtOwnedShipList;
grdOwnedShipList.DataBind();

// セッションからチェックボックスの状態を取得
var checkedStates = Session["checkbox"] as Dictionary;
// データが存在するか確認
if (checkedStates != null)
{
//最新のグリッドビューを1行ずつ見ていく
foreach (GridViewRow row in grdList.Rows)
{
//データ行か念のため確認
if (row.RowType != DataControlRowType.DataRow)
{
continue;
}
//行を特定する為のキーとして[ID]を取得する
string ID = grdList.DataKeys[row.RowIndex].Value.ToString();
CheckBox chk = row.FindControl("chk") as CheckBox;

//キーを元にチェックボックス復元
if (chk != null && checkedStates.ContainsKey(shipId))
{
chk.Checked = checkedStates[shipId];
}
}
}

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?