Search code examples
c#user-controlsdesign-principles

Having trouble understanding User Controls in C#


I'm new to usercontrols, having only created one so far, so bear with me. I've been reading today that usercontrols are supposed to be self-contained and not rely on any information from the parent container. I get that part, but what I'm having trouble understanding is the "right" way to design my program around that principle.

I'm making a web form in C# in which there's a page with a usercontrol in that page. I've made the usercontrol in its ascx file and dragged it into my aspx page. The usercontrol is a couple date boxes and a gridview to show the results of an SQL stored procedure.

I'd really like to reuse this control, but I can't figure out how to "tell" the usercontrol what stored procedure I'd like to run for the specific page I'm on without violating the "don't rely on the parent container" rule.

Thanks


Solution

  • Don't rely on the parent container doesn't mean you can't communicate. Expose a property in the user control which the parent will set. But have a default value so it doesn't crash.

    Also, if this is a very specific control, there's no reason it would be bad to rely on the parent. It might not be ideal, but you would be using the user control to provide a separation of code.