What is the best way to do validations in windows forms - c#

What is the best way to do validation in a windows forms application?
What is the easiest way?
What is the most attractive (to the end user) way?
Regards,
-Kushan-

Concerning UI validation, I have a set of control validators, and I just plug 'em in where I need them by assigning their control. You can show errors using ErrorProvider, all you need is encapsulated framework to automate things.
First there is the ValidatorBase class. Make it abstract and inherit the Component class so you can have design time support. Store a private instance of ErrorProvider here, and use something like Template Method pattern (create a Validate method, which in turn calls the protected abstract DoValidation method). In concrete implementations of the base class just override the DoValidation and put your logic here. You can have EmptyValidator (check if control's value isn't empty), RegexValidator (check controls value with some reg. expression), GroupValidator (do Validate on every ValidatorBase instance in some list), whatever you want.
In the base class, you can add things like design-time support for properties (the error message, icon, control to validate etc...)
EDIT1: Now, concerning validation other then in the UI, that is the domain of your business layer, and your rules. There are frameworks / patterns for those things too, but I think you are asking about the UI validation.
EDIT2: ASP.NET has a set of similar validators built-in, although with more functionalities (client side validation, etc...), but to be honest, I don't like them that much.
EDIT3: also check:
Is there any validation control available in .net win forms like asp.net web form?

One interface you might consider looking at is IDataErrorInfo along with the ErrorProvider class. I've got an old blog post that provides a list of the DataBinding classes and interfaces that might help: Data Binding Classes, Interfaces, and Attributes in Windows Forms 2.0.

Related

Is it common practice to extend a WinForm control using a custom component wrapper as opposed to inheritance?

I've recently been adding custom features to some of the various WinForms Controls by creating custom Component derived classes which just wrap the Control, hooking into the needed events to perform the extra functionality.
For instance, I wanted to add drag-and-drop functionality to a few different ListBox controls in my application, so I created a DragAndDropListBoxComponent which inherits from the Component class, then add this new component to the Forms I needed to add the functionality to, setting the DragAndDropListBoxComponent's ListBox property to the list box I wanted to add the functionality to.
I like this method of extending standard Control functionality because I can create more than one custom behavior type of Component for the same Control and mix them together for some interesting effects. This also favors the Composition over Inheritance principle.
It seems to have taken me awhile to come to the realization of using Component class list this. This is partly due to never seeing it used in such a way online - hence my question. Are custom Component classes commonly used in this way?
There are other options, which one you pick doesn't matter all that much as long as it achieves the desired result and you do not have the feeling your solution is working against you at every turn.
A possible alternative is using an Extender Provider. One advantage of the Extender Provider is that you seemingly add an "AllowDragAndDrop" property to each Control. (in your case the property would be added only to ListBox instances)
This new property is visible at Design Time so other consumers don't have to know the implementation nor location details of the DragAndDrop functionality, they only have to set a property in the PropertyGrid.
Another possible alternative is using the Decorator pattern. This is for example used in .NET streams: You have a stream and then you add additional behavior (buffering, (un)zipping, encryption, ...) by creating a new stream that takes the old one as a constructor parameter. In your case you would wrap a ListBox in a DragAndDropListBox. Be careful though, this approach might cause your more trouble than advantages in this particular case.
Yet another possible alternative is inheriting from the controls you want to extend and add a list of "CustomBehaviors" to the controls. CustomBehaviors would implement some interface which allows you to add new behavior to the control by adding a concrete instance of the interface to the collection.

polymorphism with Windows Forms

I'm making a project to get myself more familiar with Windows Forms and Graphic User Interfaces.
I have created this program for the Department of Motor Vehicles that uses polymorphism in CONSOLE. So when I input a taxi, it will call the base class of an industrial vehicle rather than a personal vehicle.
The program works fine in console.
But I'm wondering if that's implementable through a Graphical Interface. I know I can just have buttons with the types of vehicles, then have a new form open up to input that data for that specific type of vehicle. But that wouldn't be polymorphism....
Is this a type of project that could be done with polymorphism? and GUI's or no?
I think you would get more bang for the buck if only one form was created which handled the base class as mentioned. But it would turn on/off or make visible items as required by the derived classes. The GUI doesn't have to be polymorphic, it just needs to handle the polymorphism of the data. HTH
You'll have to be more specific about what you want to achieve. Polymorphism can be applied to most problems, if you like. Whether or not it's a good technique varies, and depends very much on how you use it. You seem to be forming ideas about how your object hierarchy will work early on, whereas I would suggest that you don't start there - instead specify what your application should do and how it should do it, and design your object model around that. It may turn out that your idea of how to represent (given your example) a taxi actually isn't useful.
There is no reason why you can't benefit from polymorphism in any object-oriented application, regardless of what user interface you elect to use. In your scenario, it may make sense to use only references to the base class in your list view, and then open up the appropriate details view suited to the specific type of the object.
Also, I recommend WPF for what it's worth. There's no use learning Windows Forms now unless you have a very good reason.
Perhaps what you are looking for is a way to dynamically build your GUI according to the type of (polymorphic) object you are passing? This can be done by using reflection, asking the object passed to the Form which attributes or properties it has and generate automatically input fields, text boxes etc. for each attribute.
For some examples, read this SO post:
Dynamic options dialog (using reflection)

accessing Winform`s private UI Component into another class in C#

I have WinForm which is a tab based and including all Tabs it has around 60 UI Components. Depending upon value selected in some UI Components i am Auto filling rest of the UI components.For this i would like to write a helper class.But the problem is if i pass Winform object to that class i am not able to access values on that Form because all the member are declared private.
one possible solution is that I can write around 60 properties in the Winform but i think this is not the best way to do it. I would like to know what is the best way to handle problem like these ?
You could change the Modifiers for your UI components from private to internal. This would allow all classes within the same project to directly access the components.
However, I would argue that exposing the necessary components through properties is a better design than exposing them publically/internally. I acknowledge that it includes a fair amount of typing, but it's safer as you can expose them cleanly, in a manner specific to your use case.
That being said - there are a couple of things I would consider:
Can this be refactored into a smaller class, using fewer components by using UserControls? This might make it more managable, as well as promote reuse. 60 UI elements is a fair amount for a single screen.
Can you refactor this to pass the data, instead of trying to work with the controls directly? For example, you could auto-fill the data via a shared interface, and data bind the controls to the data, or something similar.
You can declare the members of a WinForm as public protected, protected internal, and internal. You can do this either in the properties window for a specific component (go to the Modifiers property) or you can change them in the Designer of the form (they are declared after the "Windows Form Designer generated code").
If you don't want to make the members public, nor make a property or method to get that information, then all you're left with is attempting to get the value via reflection, which is perhaps the worst option of all three.
Your best solution would be to make properties for each of those private members and expose them that way.
One way to approach this is to create a class that contains all of the data that you want to bind to (e.g. a class that implements INotifyPropertyChanged).
Then share this instance between the WinForm and the other class. Voila!

Notify Gui that data class has changed

In C#:
I have a data class that is shared amongst several gui classes. I would like all of the gui classes that use it to be notified when some of the properties change, so they can keep the GUI up to date.
In a couple of the properties I have added delegates that the GUI classes can listen to for updates. This seems to work ok.
The problem I have is that more and more of the properties will require GUI notification. When that happens I will have to add more delegates. It also seems that this is adding an extra responsibility to the data class that it has to manage.
Is there some common pattern that I can use to monitor this class to extract this notification responsibility from the data class?
The common way of doing this is for the data class to implement INotifyPropertyChanged.
EDIT: If you have a lot of properties, this can lead to very repetitive code in the data class, and if you are binding to a UI, it might be best to use an AOP approach and intercept calls to the properties that you want to notify on. Most IoC containers have support for this sort of thing.
The pattern is called Observer. In .Net, events are one implementation of that pattern.
For the specific case of observing individual properties, the INotifyPropertyChanged interface should be used (as #Lee describes).
You don't say what GUI framework (WinForms, WPF) you are using, but there is the INotifyPropertyChanged interface. There is an How to guide on MSDN too.
You can just use the built-in System.EventHandler. That is a pretty standard pattern. You still need to define an event for each property that you want to monitor, but you don't need a separate delegate.
In Windows Forms there are several ways to notify GUI when some properties are chaged using Data Binding.
There are several types of Data binding in Windows Forms.
For simple data binding (data source with one object boud to one control) you can use INotifyPropertyChanged, or you can add events in this format: PropertyNameChanged for every property that you want update in GUI. And you should set Binding.ControlUpdateMode property to OnPropertyChanged.
For complex data binding (data source with many objects bound to control that can display many objects) you should use all from (1) and you should use BindingSource or BindingList or manually implement IBindingList;
For more information you should see this great books:
Windows Forms 2.0 Programming by Chris Sells
Data Binding with Windows Forms 2.0: Programming Smart Client Data Applications with .NET by Brian Noyes

How to avoid duplicating logic on two similar WinForms?

I have two forms, form A and form B. These forms must differ in appearance, but they share a lot of logic. The problem is that this logic is tied to the appearance (validation on button click, events being fired, etc.). For example, I have a name field, and when the save button is pressed, I need to fire an event which causes the parent form to validate the record name to avoid duplicates. Both forms need this logic, but their save buttons are in different places, and the tooltip that is shown when an error occurs also needs to appear in a different place. This is just one example, but does anyone know of a way that I can avoid copying and pasting code here? Perhaps I am missing something obvious...
You could create an object with data that is represented in both forms, and put validation logic in that object. The presentation layer should populate that object with the entered data, ask the object to validate itself, and then handle validation errors in a form-specific way.
If the common logic is UI related you need to create your own custom form class (that inherit from Form class) with the desired logic. then all you need to do is inherit that class in your forms.
If the common logic is less UI related create an internal class that encapsulates the common logic and call it from both forms.
You need to add a Controller between your 2 views and your shared model. This way you will just need to do : myController.save(); instead having to call you model object to save them in both winform.
There are few ways that I can think of to refactor these forms to share logic. You could use one or more of these in conjunction:
Create UI specific "bean" objects that wrap your business object and adds additional functionality that is shared between forms. This bean can do things like create tool tips, assist with validation, eventing, etc.
Create a helper class with common functions. Generalize the logic on the two forms to call this helper class for common functions.
Enhance your business objects to do your validation. I don't mean to say your BOs should be aware of any UI, but they could/should enforce the business rules. This might pull some of the validation logic off your forms and into a common location.
Create custom controls that are specific to the type of data with which you are working, and use those controls on the two forms.
You may also want to take a look at the CSLA Framework, I've used it pretty successfully in past projects to help reduce the amount of duplicate code between different UIs. It takes advantage of .NET's databinding capabilities, but I don't think it's required to use databinding just to get the most out of the framework.

Categories

Resources