Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the purpose of User Controls in Visual C#?

User Controls -- Do they serve a special purpose?

As far as I can tell they are no different to forms - they have the same toolbox and features.

Are there certain times when they are appropriate to use over forms? It would be interesting to understand what they are good for.

like image 694
Ric Avatar asked Sep 04 '09 14:09

Ric


2 Answers

You use them to group a set of controls and behaviors together in a re-usable way. You can't show a control on the screen unless it's added to a form somewhere.

One good example is a textbox. It's very common to have a label next to your textboxes. You can build a user control to make this easier. Just drop a label and a textbox on the control, expose whatever your properties you want, setup the new control in your toolbox, and now you can just drop this control on your form instead of needing to arrange a label and a toolbox on the form separately.

You could kind of think of them as a panel which "remembers" what controls you put on it. And there's one more important piece. You can put code in these controls as well, and use that to also build special behaviors into your custom controls.

like image 109
Joel Coehoorn Avatar answered Oct 26 '22 22:10

Joel Coehoorn


I have to disagree (slightly) with the selected answer. Reusability is only part of what a UserControl is for.

All Controls are reusable. Almost all controls are reusable on the same Form/Window/Panel/etc. For example, a TextBox is a control.

There are two ways to create your own reusable control:

  1. Custom Control
    • Completely custom, and reusable.
    • Created entirely in code.
    • You get a bit more granular control over what your control is doing this way.
    • Lighter weight (usually), because there isn't anything added in for designability within Visual Studio.
    • In ASP.Net only: No "HTML" type file to use or edit.
  2. User Control
    • Completely custom, and reusable.
    • Created partially in a designer in Visual Studio, and partially in code. (via code behind)
    • Much easier to deal with from a visual aspect.
    • A little heavier, as there is pre-existing code added in by the framework to support designing inside Visual Studio.
    • In ASP.Net only: You can change the appearance a bit simply by editing the .ascx file (basically HTML).
like image 33
Ben Lesh Avatar answered Oct 26 '22 22:10

Ben Lesh