ページ内に複数のドロップダウンリストがあり、ユーザーがdisable allと書かれたチェックボックスを選択した場合、すべてを無効にしたいと思います。今のところ、私はこのコードを持っていますが、それは動作しません。何か提案はありますか?
foreach (Control c in this.Page.Controls)
{
if (c is DropDownList)
((DropDownList)(c)).Enabled = false;
}
各コントロールは子コントロールを持つので、それらすべてに到達するためには再帰を使用する必要があります。
protected void DisableControls(Control parent, bool State) {
foreach(Control c in parent.Controls) {
if (c is DropDownList) {
((DropDownList)(c)).Enabled = State;
}
DisableControls(c, State);
}
}
そして、このように呼び出します。
protected void Event_Name(...) {
DisableControls(Page,false); // use whatever top-most control has all the dropdowns or just the page control
} // divs, tables etc. can be called through adding runat="server" property
これは再帰的に行う必要があり、つまり、コントロールの子コントロールを.NETに無効化する必要があるのです。
protected void Page_Load(object sender, EventArgs e)
{
DisableChilds(this.Page);
}
private void DisableChilds(Control ctrl)
{
foreach (Control c in ctrl.Controls)
{
DisableChilds(c);
if (c is DropDownList)
{
((DropDownList)(c)).Enabled = false;
}
}
}