Tải bản đầy đủ - 0 (trang)
7-17. Validate an Input Control

7-17. Validate an Input Control

Tải bản đầy đủ - 0trang

CHAPTER 7 ■ WINDOWS FORMS



Solution

Use the ErrorProvider component to display an error icon next to the offending control. Check for

errors before allowing the user to continue.



How It Works

You can perform validation in a Windows-based application in a number of ways. One approach is to

refuse any invalid character as the user presses a key, by using a MaskedTextBox control, as shown in

recipe 7-8. Another approach is to respond to control validation events and prevent users from changing

focus from one control to another if an error exists. A less invasive approach is to simply flag the

offending control in some way so that the user can review all the errors at once. You can use this

approach by adding the ErrorProvider component to your form.

The ErrorProvider is a special property extender component that displays error icons next to invalid

controls. You show the error icon next to a control by using the ErrorProvider.SetError method and

specifying the appropriate control and a string error message. The ErrorProvider will then show a

warning icon to the right of the control. When the user hovers the mouse above the warning icon, the

detailed message appears.

You need to add only one ErrorProvider component to your form, and you can use it to display an

error icon next to any control. To add the ErrorProvider, drag it on the form or into the component tray

or create it manually in code.



The Code

The following example checks the value that a user has entered into a text box whenever the text box

loses focus. The code validates this text box using a regular expression that checks to see if the value

corresponds to the format of a valid e-mail address (see recipe 2-5 for more details on regular

expressions). If validation fails, the ErrorProvider is used to display an error message. If the text is valid,

any existing error message is cleared from the ErrorProvider.

Finally, the Click event handler for the OK button steps through all the controls on the form and

verifies that none of them have errors before allowing the example to continue. In this example, an

empty text box is allowed, although it would be a simple matter to perform additional checks when the

OK button is pressed for situations where empty text boxes are not acceptable. Figure 7-12 shows how

the ErrorProvider control indicates an input error for the TextBox control when Recipe07-17 is run.



348



www.it-ebooks.info



CHAPTER 7 ■ WINDOWS FORMS



using System;

using System.Windows.Forms;

using System.Text.RegularExpressions;

namespace Apress.VisualCSharpRecipes.Chapter07

{

public partial class Recipe07_17 : Form

{

public Recipe07_17()

{

// Initialization code is designer generated and contained

// in a separate file named Recipe07-17.Designer.cs.

InitializeComponent();

}

// Button click event handler ensures the ErrorProvider is not

// reporting any error for each control before proceeding.

private void Button1_Click(object sender, EventArgs e)

{

string errorText = "";

bool invalidInput = false;

foreach (Control ctrl in this.Controls)

{

if (errProvider.GetError(ctrl) != "")

{

errorText += " * " + errProvider.GetError(ctrl) + "\n";

invalidInput = true;

}

}

if (invalidInput)

{

MessageBox.Show(

"The form contains the following unresolved errors:\n\n" +

errorText, "Invalid Input", MessageBoxButtons.OK,

MessageBoxIcon.Warning);

}

else

{

this.Close();

}

}

// When the TextBox loses focus, check that the contents are a valid

// e-mail address.

private void txtEmail_Leave(object sender, EventArgs e)

{

// Create a regular expression to check for valid e-mail addresses.

Regex regex = new Regex(@"^[\w-]+@([\w-]+\.)+[\w-]+$");



349



www.it-ebooks.info



CHAPTER 7 ■ WINDOWS FORMS



// Validate the text from the control that raised the event.

Control ctrl = (Control)sender;

if (String. IsNullOrEmpty(ctrl.Text) || regex.IsMatch(ctrl.Text))

{

errProvider.SetError(ctrl, "");

}

else

{

errProvider.SetError(ctrl, "This is not a valid email address.");

}

}

[STAThread]

public static void Main(string[] args)

{

Application.Run(new Recipe07_17());

}

}

}



Figure 7-12. A validated form with the ErrorProvider



7-18. Use a Drag-and-Drop Operation

Problem

You need to use the drag-and-drop feature to exchange information between two controls (possibly in

separate windows or separate applications).



Solution

Start a drag-and-drop operation using the DoDragDrop method of the Control class, and then respond to

the DragEnter and DragDrop events in the target control.



350



www.it-ebooks.info



CHAPTER 7 ■ WINDOWS FORMS



How It Works

A drag-and-drop operation allows the user to transfer information from one place to another by clicking

an item and dragging it to another location. A drag-and-drop operation consists of the following three

basic steps:

1.



The user clicks a control, holds down the mouse button, and begins dragging.

If the control supports the drag-and-drop feature, it sets aside some

information.



2.



The user drags the mouse over another control. If this control accepts the

dragged type of content, the mouse cursor changes to the special drag-anddrop icon (arrow and page). Otherwise, the mouse cursor becomes a circle

with a line drawn through it.



3.



When the user releases the mouse button, the data is sent to the control, which

can then process it appropriately.



To support drag-and-drop functionality, you must handle the DragEnter, DragDrop, and (typically)

MouseDown events. To start a drag-and-drop operation, you call the source control’s DoDragDrop method.

At this point, you submit the data and specify the type of operations that will be supported (copying,

moving, and so on). Controls that can receive dragged data must have the AllowDrop property set to true.

These controls will receive a DragEnter event when the mouse drags the data over them. At this point,

you can examine the data that is being dragged, decide whether the control can accept the drop, and set

the DragEventArgs.Effect property accordingly. The final step is to respond to the DragDrop event, which

occurs when the user releases the mouse button.



■ Note It is very important that the Main method of your Windows application be annotated with the STAThread

attribute if your application will provide drag-and-drop functionality.



The Code

The following example allows you to drag content between a RichTextBox and a standard TextBox

control. Using the standard TextBox, it is not possible to drag only the currently selected text because as

soon as you click the selected text to initiate a drag operation, the selection is cleared. Even handling the

MouseDown event will not allow you to work around this because the selected text is already cleared by the

event is raised.

However, the RichTextBox leaves the selection in place, avoiding the problem. Unfortunately, the

RichTextBox has quirks of its own. To drop successfully onto a RichTextBox, you must be holding down

the Ctrl key when you let go of the mouse button. You can also use the example with other applications

that support text drag-and-drop operations.



351



www.it-ebooks.info



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

7-17. Validate an Input Control

Tải bản đầy đủ ngay(0 tr)

×