C#使用ErrorProvider淺析
用戶在使用我們編寫的程序時,難免會出現(xiàn)輸入錯誤的現(xiàn)像,用戶如何知道你輸入的內(nèi)容是在那個地方出錯了呢?這里我們用ErrorProvider來幫助我們。
C#使用ErrorProvider過程如下:
1、定義ErrorProvider
2、C#使用ErrorProvider的SetError方法設(shè)置需要錯誤提示的控件及提示方法
例如下例,因為整數(shù)不能為零,所以當輸入零時,會在Text控件右邊出現(xiàn)一個警告提示。
- namespace GetNewGuid{
- public partial class GetGUID : Form{
- //1、ErrorProvider:提供表單上的控制項有與其相關(guān)的錯誤。
- ErrorProvider epProvider = new ErrorProvider();
- public GetGUID(){
- //得到指定數(shù)量GUID事件
- btnGetGUID.Click += new EventHandler(btnGetGUID_Click);
- }
- }
- // 得到GUID按鈕事件方法
- private void btnGetGUID_Click(object sender, EventArgs e){
- //清空錯誤
- epProvider.Clear();
- if (txtGUID.Text.Substring(0, 1) != "0"){
- //……
- }
- else{
- //2、錯誤提示
- epProvider.SetError(txtGUID, "GUID數(shù)量只能為整數(shù),請輸入大於零的整數(shù)!");
- //焦點定位到錯誤處
- txtGUID.Focus();
- //選擇輸入的錯誤
- txtGUID.SelectAll();
- }
- }
- }
同時我們也可以對ErrorProvider進行相關(guān)的設(shè)定。
region 定義ErrorProvider的相關(guān)屬性
- //BlinkStyle:取得或設(shè)定錯誤圖示閃爍的速率。
- epProvider.BlinkStyle = ErrorBlinkStyle.BlinkIfDifferentError;
- //BlinkRate:取得或設(shè)定數(shù)值,表示錯誤圖示何時閃爍。
- epProvider.BlinkRate =50;
- #endregion
開發(fā)者可以自己設(shè)定需要的屬性。以上介紹C#使用ErrorProvider
【編輯推薦】