31 December 2012

Error Provider in Windows Application

Error Provider is a very useful for Application Validation.
Create Simple form.
Drag and Drop two Text Boxes and Buttons.
TextBox Names are txtUsername,txtPassword
Button Names are btn_Ok,btn_Cancel.
Button Text are &Ok,&Cancel.
Copy and Paste the following code in your Coding Section

 private void btn_Cancel_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
        private void btn_Ok_Click(object sender, EventArgs e)
        {
            if (txtUserName.Text.Length == 0 && txtPassword.Text.Length == 0)
            {
                DispayErrorProvider(txtUserName);
                DispayErrorProvider(txtPassword);
            }
            else if (txtUserName.Text.Length == 0 )
            {
                DispayErrorProvider(txtUserName);
            }
            else if (txtPassword.Text.Length == 0)
            {
                DispayErrorProvider(txtPassword);
            }
            else
            {
                MessageBox.Show("Validate successfully");
            }
         }
        private void txtUserName_TextChanged(object sender, EventArgs e)
        {
            DispayErrorProvider(txtUserName);
        }
        void DispayErrorProvider(TextBox txt)
        {
            if (txt.Text.Length > 0)
            {
                errorProvider1.Clear();
            }
            else
            {
                errorProvider1.SetError(txt, "Input doesn't Empty");
            }
        }
        private void txtPassword_TextChanged(object sender, EventArgs e)
        {
            DispayErrorProvider(txtPassword);
        }
        private void txtUserName_Leave(object sender, EventArgs e)
        {
            DispayErrorProvider(txtUserName);
        }
        private void txtPassword_Leave(object sender, EventArgs e)
        {
            DispayErrorProvider(txtPassword);
        }

Run the Application.
Press Alt+O Button .Error Provider will display in the Screen.
Press Alt+C Application will exit.
Type your User name and Password .Error provider will not display in the Screen.
Note Use Only Keyboard.

No comments: