ErrorProvider コンポーネントは、効果的に使用するのが非常に厄介です。これは修正可能ですが、いくつかの新しい機能でコンポーネントを拡張する C# の例を示します。
- ShowError(Control ctl, bool enable) は、 enable引数が trueの場合、設計時に入力したテキストを表示します。SetError() の使いやすいバージョン。
- アクティブな警告アイコンが表示されている場合、HasErrors は true を返します。OK ボタンの Click イベント ハンドラーで便利です。
- FocusError() は、警告アイコンがある最初のコントロールにフォーカスを設定します (存在する場合)。警告が残っていない場合はfalseを返します。
- SetError() は、ErrorProvider.SetError() の代替です。フォームの Load イベントが発生した後にコントロールを追加する場合、または警告テキストを変更する必要がある場合にのみ必要です。
プロジェクトに新しいクラスを追加し、以下に示すコードを貼り付けます。コンパイル。ツールボックスの上部からフォームにドロップします。設計時の動作は同じです。適度にテストされています。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
using System.ComponentModel.Design;
class MyErrorProvider : ErrorProvider {
public void ShowError(Control ctl, bool enable) {
// Easy to use version of SetError(), uses design-time text
if (!enable) base.SetError(ctl, "");
else {
if (errors.ContainsKey(ctl)) base.SetError(ctl, errors[ctl]);
else base.SetError(ctl, "No error text available");
}
}
public bool HasErrors {
// True if any errors are present
get {
foreach (var err in errors)
if (!string.IsNullOrEmpty(base.GetError(err.Key))) return true;
return false;
}
}
public bool FocusError() {
// Set the focus to the first control with an active error
foreach (var err in errors) {
if (!string.IsNullOrEmpty(base.GetError(err.Key))) {
err.Key.Focus();
return true;
}
}
return false;
}
public new void SetError(Control ctl, string text) {
// Use this only to add/modify error text after the form's Load event
if (!string.IsNullOrEmpty(text)) {
if (errors.ContainsKey(ctl)) errors[ctl] = text;
else errors.Add(ctl, text);
}
base.SetError(ctl, text);
}
private void initialize(object sender, EventArgs e) {
// Preserve error text
copyErrors(((Form)sender).Controls);
}
private void copyErrors(Control.ControlCollection ctls) {
foreach (Control ctl in ctls) {
var text = this.GetError(ctl);
if (!string.IsNullOrEmpty(text)) {
errors.Add(ctl, text);
base.SetError(ctl, "");
}
copyErrors(ctl.Controls);
}
}
private Dictionary<Control, string> errors = new Dictionary<Control, string>();
// Plumbing to hook the form's Load event
[Browsable(false)]
public new ContainerControl ContainerControl {
get { return base.ContainerControl; }
set {
if (base.ContainerControl == null) {
var form = value.FindForm();
if (form != null) form.Load += initialize;
}
base.ContainerControl = value;
}
}
public override ISite Site {
set {
// Runs at design time, ensures designer initializes ContainerControl
base.Site = value;
if (value == null) return;
IDesignerHost service = value.GetService(typeof(IDesignerHost)) as IDesignerHost;
if (service == null) return;
IComponent rootComponent = service.RootComponent;
this.ContainerControl = rootComponent as ContainerControl;
}
}
}