views:

14

answers:

2

Hi there,

I have created a usercontrol to capture education details, it contains 5 textboxes and an functionto insert that values into my db. I have added the usercontrol 5 times to a page. I have a button on my aspx page which I want to be able to click and call the function to insert the values.

Can anyone suggest how I can do this?

+1  A: 

The function which inserts values into your db should not be in your usercontrols but in your page. Does your usercontrol has a save button itself or only the page? On first variant you should raise an event and the page could catch it to save the values. On second variant you should iterate through your usercontrols(added dynamically or fixed?). You should add public properties which return the textbox's values to the page, then you can save these values into the db.

Tim Schmelter
Hi Tim, No I only have a single button to submit the insert. So should I have public properties doing a get set on the textbox values? not sure if thats what you meant.What are the benefits of having the insert method within the page?
Your Usercontrol's intended use is to show the user and let him enter text. You could reuse this control on several pages when designed simple. The more specialized a control is the more unreusable it will be. Data Access belongs to the model and not into the view. So you could change the model without to change your usercontrols. Or you can use the model in different applications(windows apps, webservice, etc.) without having to extract the data access functionality out of your controls which belong to asp.net only.
Tim Schmelter
I would have the save function in the page, iterate through the usercontrols and get their values from public properties(internally reference the textboxes'-Text property) and save them to database(or better use a model class or project to handle data access centralized).
Tim Schmelter
Thanks Tim for your advise. I will look into this as what you say makes total sense.
A: 

Put a public method on your user control.

// Inside MyUserControl
public void SaveIt() {
    // logic to perist the values to db.
}

From your ASPX page (or code behind) when the button is clicked, loop over your user control instances and call the method:

// On Click...

MyUserControl[] arrControls = new MyUserControl[] {myUC1, myUC2, myUC3, myUC4, myUC5};
foreach (MyUserControl c in arrControls)
    c.SaveIt();
John K
A usercontrol belongs to the view, data access should be separated in the model (or at least the controller=page). Otherwise a usercontrol might not be very reusable in my opinion.
Tim Schmelter
Thanks jdk. Never thought it was that easy :)
@diver-d: Indeed! Even though they're UI/visual controls, they're also pure .NET classes, so the same OO features like encapsulation, access modifiers and references can be used to send messages back and forth between them, just like regular objects.
John K