ASP.NetWebサイトのページの機能を少し変更する作業をしています。元のページには、項目がハードコーディングされていないチェックボックスリストがページに書き込まれていました。
代わりに、最初のレンダリングで、cblはクエリの結果にデータバインドされます。
sSQL = "select query here";
using (SqlConnection dbcon = new DataAccess().OpenDb())
{
using (SqlDataReader dr = new SqlCommand(sSQL, dbcon).ExecuteReader())
{
cbl.DataTextField = "description";
cbl.DataValueField = "productid";
cbl.DataSource = dr;
cbl.DataBind();
}
dbcon.Close();
}
ポストバックで次のコード:
foreach (ListItem li in cbl.Items) { if (li.Selected) rtnQS += li.Value + ","; }
チェックボックスリストの動的データバインドリスト項目を調べて、チェックされた値を取得します。同じことを試みました。ページに空のテーブルを配置してから、動的に行を作成しました。
sSQL = "similar select query here";
using (SqlConnection dbcon = new DataAccess().OpenDb())
{
using (SqlDataReader dr = new SqlCommand(sSQL, dbcon).ExecuteReader())
{
while (dr.Read())
{
TableRow tr = new TableRow();
TableCell tc = new TableCell();
CheckBox chk = new CheckBox();
chk.Text = dr["description"].ToString();
chk.InputAttributes.Add("id", dr["id"].ToString());
chk.Checked = true;
tc.Controls.Add(chk);
TableCell tc2 = new TableCell();
if (Convert.ToBoolean(dr["controlcondition"]))
{
CheckBoxList cbl_sub = new CheckBoxList();
cbl_sub.Attributes.Add("for", dr["id"].ToString());
sSQL = "subquery";
using (SqlConnection newcon = new DataAccess().OpenDb())
{
using (SqlDataReader br = new SqlCommand(sSQL, newcon).ExecuteReader())
{
cbl_block.DataTextField = "subname";
cbl_block.DataValueField = "subid";
cbl_block.DataSource = br;
cbl_block.DataBind();
}
}
tc2.Controls.Add(cbl_sub);
}
else
{
TextBox txtSub = new TextBox();
txtSub.Attributes.Add("for", dr["id"].ToString());
tc2.Controls.Add(txtSub);
}
tr.Cells.Add(tc);
tr.Cells.Add(tc2);
tblDispatchOpt.Rows.Add(tr);
}
}
dbcon.Close();
}
唯一の問題は、イテレータがテーブルに到達すると、ハードコードされたヘッダー行のみを読み取ることです。(ただし、テーブルは元のページのすべての正しい属性で美しくレンダリングされます。)
テーブルの行を読み取ろうとするコードは次のとおりです。
foreach (TableRow row in tblDispatchOpt.Rows)
{
TableCell cell = row.Cells[0];
++counter;
foreach (Control c in cell.Controls)
{
if (c is CheckBox)
{
CheckBox cb = (CheckBox)c;
if (cb.Checked && cb.Attributes["ttid"] != null) dtTTInfo.Rows.Add(cb.Attributes["ttid"].ToString(), "", "");
}
}
}
デバッグラベルチェックで、行が1つだけで、ハードコードされたヘッダー行であることがわかります。したがって、ページは他の行を読み取るときにそれらが存在するとは信じていないように見えるため、基本的に他の行を読み取りません。
では、なぜそれがテーブルで機能しないのですか?または、レンダリングやライフサイクルなど、ポストバックの動的コントロールでは機能しないという通常の理由でテーブルで機能しない場合、チェックボックスリストで機能するのはなぜですか?