0

I have a Form that emulates a virtual (on screen) keyboard with a DataGridView. This form is in a library that I want to keep it decoupled from the data layer. How can I pass this form a method to search the database and return a DataTable which I can display in the Form?

public partial class AlphaKeypad : Form
{
    public AlphaKeypad(delegate here)
    {
        ...
    }
}

How will I use the delegate in that form?

EDIT: I wasn't very clear in my original question, so I edited a little:

In MainForm() I have a method called Search like this:

public DataTable Search(string filter)
{
    ...
}

I want to pass that method to AlphaKeypad() to be handled this way: When the user presses some keys, I want to call the Search() function with the text entered, and display in AlphaKeypad's dridview the returned DataTable from the database.

Hope this is clear now.

Thanks!

H Mihail
  • 613
  • 8
  • 18

2 Answers2

1

Just write a method like this

public DataTable FindMatchingElements(String searchTerm)
{
    // ToDo: Search within the database and return a DataTable with the desired results.
}

Your AlphaKeypad then needs to get such a method:

public class AlphaKeypad
{
    private Func<String, DataTable> _SearchMethod;

    public void SetSearchMethod(Func<String, DataTable> searchMethod)
    {
        _SearchMethod = searchMethod;
    }

    private void OnStartSearching()
    {
        var enteredSearch = GetKeywordsEnteredByUser();
        var dataTable = _SearchMethod(enteredSearch);

        Visualize(dataTable);
    }
}

From the outer world you can then do:

private void InitializeAlphaKeypad()
{
    var alphaKeypad = new AlphaKeypad();
    alphaKeypad.SetSearchMethod(MyDatabaseClass.FindMatchingElements);
}
Oliver
  • 43,366
  • 8
  • 94
  • 151
  • It doesn't compile, I get `The type or namespace Func could not be found` – H Mihail Dec 14 '15 at 12:49
  • @HMihail: The full name (without using statements) would be `System.Func`. For the `DataTable` type you have to add an reference to `System.Data`. – Oliver Dec 15 '15 at 07:25
0
public AlphaKeypad(Func<DataTable> func) {
    ....
}

// somewhere else
new AlphaKeypad(()=> return new DataTable());

// or
DataTable FunctionReturningDataTable() {
    return ....;
}
....
new AlphaKeypad(FunctionReturningDataTable); // no brackets means, the function will be passed, not the result of call
TcKs
  • 25,849
  • 11
  • 66
  • 104
  • Will I be able to control also the search string created by the virual keyboard? I forgot to mention that in the question. – H Mihail Dec 14 '15 at 12:21
  • The delegate is reference to regular method (function). You can do whatewer you want in the method. – TcKs Dec 14 '15 at 12:23
  • I added some details, since I am still confused. Can you please check it out? – H Mihail Dec 14 '15 at 12:35