UserControls

  • Thread starter Thread starter Kim
  • Start date Start date
K

Kim

Im kind of new to the C# world so please bear with me. I have a form
that contains a navagation bar in the bar is a listing of clients. I
also have a usercontrol that has a bunch of textboxes that will fill
the data on a client. My problem that Im having is once the user
clicks on a clients name in the form I need for the textboxes in the
usercontrol to populate with the data. Ive tired alot of diffent ways
to do this but what I need to do is have some type of eventhandler to
fire so it will populate. Is it possible to pass an eventhandler from a
form to a usercontrol? Any help would be greatly appreciated.
Thanks
Kim
 
The right way to do this is to use what's called the
Model-View-Presenter pattern, but since you're just getting started,
perhaps it makes more sense to do it the _easiest_ way.

The easiest way is to add properties to your text box user control. For
example, if one of the text boxes contains the client name, your user
control should expose a public ClientName property:

public string ClientName
{
get { return this.txtName.Text; }
set { this.txtName.Text = value; }
}

where txtName is your text box containing the name. You can do this
with all of the values in your user control.

Then, in the form that contains the user control, wire up the
navigation bar event with the user control properties. Let's say that
the navigation bar fires a Click event when the user clicks on it.
(Sorry, I don't know much about navigation bars. I've never used one.)
So, you have an event handler in your form:

private void navBar_Click(object sender, System.EventArgs e)
{
... get the client that was clicked ...
this.clientInfoControl.ClientName = client.Name;
... set other text box entries ...
}

As well, if you want to know when things happen inside your user
control, so that the form can take some action, you can define public
events that your user control raises whenever something of interest
happens inside. For example:

public event System.EventHandler ClientNameChanged;

public void txtName_TextChanged(object sender, System.EventArgs e)
{
if (this.ClientNameChanged != null)
{
this.ClientNameChanged(this, System.EventArgs.Empty);
}
}

This way, whenever the TextChanged event is raised on your client name
text box inside the user control, the user control raises a
ClientNameChanged event of its own.

Notice that in all of this, the Form outside of the user control has no
idea how the client name is displayed or how the user control knows
that it has changed. It only knows that there is this thing called a
"client name" and that it can fetch it, set it, and discover when it
has changed.

This is a reasonably good design. Model-View-Presenter is even better,
but more involved, so this is a good starting point. Good luck.
 
Back
Top