C# 學習使用ErrorProvider

   用戶在使用我們編寫的程序時,難免會出現輸入錯誤的現像,用戶如何知道你輸入的內容是在那個地方出錯了呢?
這里我們可用ErrorProvider來幫助我們。
我們想實現下圖的效果該如何做呢?
                        
使用ErrorProvider過程如下:
1、定義ErrorProvider
2、使用
ErrorProvider的SetError方法設置需要錯誤提示的控件及提示方法

例如下例,因為整數不能為零,所以當輸入零時,會在Text控件右邊出現一個警告提示。

namespace GetNewGuid
{
    
public partial class GetGUID : Form
    {
        
//1、ErrorProvider:提供表單上的控制項有與其相關的錯誤。
        ErrorProvider epProvider = new ErrorProvider();
        
public GetGUID()
        {
            
//得到指定數量GUID事件
            btnGetGUID.Click += new EventHandler(btnGetGUID_Click);
        }
    }

        
// 得到GUID按鈕事件方法
        private void btnGetGUID_Click(object sender, EventArgs e)
        {
            
//清空錯誤
            epProvider.Clear();
            
if (txtGUID.Text.Substring(01!= "0")
            {
               
//......
            }
            
else
            {
               
//2、錯誤提示
               epProvider.SetError(txtGUID, "GUID數量只能為整數,請輸入大於零的整數!");
               
//焦點定位到錯誤處
               txtGUID.Focus();
               
//選擇輸入的錯誤
               txtGUID.SelectAll();
            } 
        }
}

當輸入0時,單擊控件,會出現下圖的錯誤提示。
         
同時我們也可以對ErrorProvider進行相關的設定。

            #region 定義ErrorProvider的相關屬性
            
//BlinkStyle:取得或設定錯誤圖示閃爍的速率。
            epProvider.BlinkStyle = ErrorBlinkStyle.BlinkIfDifferentError;
            
//BlinkRate:取得或設定數值,表示錯誤圖示何時閃爍。
            epProvider.BlinkRate =50;
            
#endregion

開發者可以自己設定需要的屬性。



原文地址:https://www.cnblogs.com/scottckt/p/984134.html