2

I am creating a User Control, and I want it to know nothing about my Database Class.

However, I need certain features from that Database Class (I need to get the Employee's name given their Employee Number).

What I would like to do is to create something in my User Control that I can wire up in my applications that use it, much like I would wire up a Click Event or something like that.

I've never actually created something like this before in a C# project, so I don't know what to call it. I would imagine it has to exist.

The function I want to call in my Database Class has this signature:

public string GetEmployeeName(int employeeNumber);

Could someone tell me what it is I am trying to do?

If it is something difficult, an example would be nice as well.

1
  • 1
    do you want to subscribe to an event? Commented Dec 20, 2012 at 16:06

3 Answers 3

5

I think what you want to do is use a delegate.

Sign up to request clarification or add additional context in comments.

3 Comments

Awesome, Nate! I knew it had to be simple.
I'll expand on this. Use a delegate to pass a method into your user control at instantiation time. The method is what will know about the database. The user control should just call this method, not knowing anything about what it does, and can just act on whatever value the method returns.
I tried creating a static delegate because I'll have about 10 of these user controls on the same form, but I get non-invocable member cannot be used like a method. I guess I have to declare this for each instance, then.
4

You can do this using a delegate e.g. Func<TArgument, TResult>;

Add a public field to your usercontrol:

//A method that has an int parameter and returns a string
public Func<int, string> GetEmployeeName;

In your user control when you need to get the employee name you can use the delegate:

string employeeName;
if (GetEmployeeName != null)
    employeeName = GetEmployeeName(employeeNumber);

You can set the delegate from the hosting page or control by doing:

myUserControl.GetEmployeeName = GetEmployeeName;

1 Comment

+1 So far, Mr. Khan, your version is the only one that compiles.
2

If your control needs to invoke a lot a business actions over the database I suggest you to write an interface and to it an instance of an implementation.

2 Comments

Sounds good, but I'm not sure how to create the interface that also contains its own code. I don't get to go down this path as often as I'd like. Is there an example of this somewhere?
@jp2code The interface cannot have any code, but the UserControl would "know" the interface, and the database class would "implement" the interface. That way your UserControl references the interface instead of your class, but is still able to call code from your class. See also: msdn.microsoft.com/en-us/library/87d83y5b(v=vs.110).aspx

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.