特集:正規表現によるテキストファイルパースVisual Studio Magazine(6/8 ページ)

» 2004年12月07日 14時05分 公開
[Francesco Balena, Marco Bellinaso,FTPOnline]

 SetInputControlColorsメソッドは、Webコントロールへ参照と、通常状態の時とフォーカスをもつ場合、それぞれの背景色と前景色を引数として受け取る。

 メソッドでは、コントロールがフォーカスを受け取ったり失ったりしたときに、指定された色に適用するクライアントサイドのJavaScriptを生成する。SetAllInputControlsColorsメソッドは、単にフォーム上のすべてのTextBox、ListBox、DropDownListコントロールについて、SetInputControlColorsメソッドを呼び出すというものだ。

リスト3■VB.NET、C#において、スタイル付きのフォーカスを設定する
' VB.NET
Sub SetInputControlColors(ByVal ctl As _
WebControl, ByVal backColor As Color, _
ByVal foreColor As Color, _
ByVal focusBackColor As Color, _
ByVal focusForeColor As Color)

Dim jsOnFocus As String = String.Format( _
"this.style.backgroundColor = '{0}';" _
& "this.style.color = '{1}';", _
focusBackColor.Name, focusForeColor.Name)
Dim jsOnBlur As String = String.Format( _
"this.style.backgroundColor = '{0}';" _
& "this.style.color = '{1}';", _
backColor.Name, foreColor.Name)
ctl.Attributes.Add("onfocus", jsOnFocus)
ctl.Attributes.Add("onblur", jsOnBlur)
End Sub

Sub SetAllInputControlsColors(ByVal parent As _
Control, ByVal backColor As Color, _
ByVal foreColor As Color, _
ByVal focusBackColor As Color, _
ByVal focusForeColor As Color)

For Each ctl As Control In parent.Controls
If TypeOf ctl Is TextBox OrElse _
TypeOf ctl Is ListBox OrElse _
TypeOf ctl Is DropDownList Then
SetInputControlColors( _
DirectCast( ctl, WebControl), _
backColor, foreColor, _
focusBackColor, _
focusForeColor)
Else
SetAllInputControlsColors(ctl, _
backColor, foreColor, _
focusBackColor, _
focusForeColor)
End If
Next
End Sub

// C#
void SetInputControlColors(WebControl ctl,
Color backColor, Color foreColor,
Color focusBackColor, Color focusForeColor)
{
string jsOnFocus = string.Format(
"this.style.backgroundColor = '{0}';" +
"this.style.color = '{1}';",
focusBackColor.Name, focusForeColor.Name);
string jsOnBlur = string.Format(
"this.style.backgroundColor = '{0}';" +
"this.style.color = '{1}';",
backColor.Name, foreColor.Name);
ctl.Attributes.Add("onfocus", jsOnFocus);
ctl.Attributes.Add("onblur", jsOnBlur);
}

void SetAllInputControlsColors(Control parent,
Color backColor, Color foreColor,
Color focusBackColor, Color focusForeColor)
{
foreach (Control ctl in parent.Controls)
{
if (ctl is TextBox || ctl is ListBox ||
ctl is DropDownList)
{
SetInputControlColors(
ctl as WebControl, backColor,
foreColor, focusBackColor,
focusForeColor);
}
else
{
SetAllInputControlsColors(ctl,
backColor, foreColor,
focusBackColor,
focusForeColor);
}
}
}

 リスト3に示したSetInputControlColorsメソッドの使い方は、たいしたことはない。

SetInputControlColors(txtFirstName, _
SystemColors.Window, _
SystemColors.WindowText, _
Color.Yellow, Color.Blue)

 フォーム上のすべての入力コントロールのためにSetInputControlColorsメソッドをひとつひとつ呼び出す代わりに、フォーム上のすべてのTextBox、ListBox、そして、DragDownListコントロールのonfocus/onblurスタイルを変更するSetAllInputControlsColorsメソッドを利用してもよい(リスト3)。

© Copyright 2001-2005 Fawcette Technical Publications

注目のテーマ