Solved

c# store function in list or call function by name

Posted on 2013-05-18
7
402 Views
Last Modified: 2013-05-18
I have a list box and when I click on it, I fire off a function corresponding to that item.

so if I click "Order History" then function OrderHistory is called.  I do this by adding strings to the listbox, then having a case statement and test the string and call a function.  I'd rather add a string and a function to some list and call it a better way.  It would save me typing

something like
List<string, function>functions;

functions.add("Order History", OrderHistory());

execute(string functionname)
functions...somehow call that function

This is basically a cheap rip off of a command pattern that I used.  this is just for one testing form and i want it to be easy.
0
Comment
Question by:jackjohnson44
  • 3
  • 3
7 Comments
 
LVL 14

Assisted Solution

by:Vel Eous
Vel Eous earned 250 total points
ID: 39177914
Perhaps something like the following (bit rough and ready):

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;

namespace Sandbox.wpf
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs args)
        {
            var selected = (sender as ListBox).SelectedItems;
            if (selected.Count > 0)
            {
                foreach (var item in selected)
                {
                    string functionToExecute = (item as ListBoxItem).Content.ToString();
                    Console.WriteLine(functionToExecute);
                    MethodInfo method = this.GetType().GetMethod(functionToExecute);
                    object result = method.Invoke(this, new object[] { "Hello World" });
                }
            }
        }

        public bool Function1(string str)
        {
            MessageBox.Show(str);
            return true;
        }

        public bool Function2(string str)
        {
            MessageBox.Show(str);
            return true;
        }
    }
}

Open in new window

0
 

Author Comment

by:jackjohnson44
ID: 39177934
Thanks!  I am having an issue though.  For some reason, my GetMethod is always null.

        private void Calling()
        {
             //always null
            MethodInfo method = this.GetType().GetMethod("FunctionToCall");
            object result = method.Invoke(this, null);
        }
        private void FunctionToCall()
        {
            MessageBox.Show("It Works");
        }
0
 
LVL 14

Expert Comment

by:Vel Eous
ID: 39177937
The GetMethod function can only reflect on public methods.
0
Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

 
LVL 75

Accepted Solution

by:
käµfm³d   👽 earned 250 total points
ID: 39178002
The GetMethod function can only reflect on public methods.
I don't believe that's accurate.

I don't see the need for Reflection here. Just populate your list box with the delegates you want to invoke.

e.g.

using System;
using System.Windows.Forms;

namespace _28132404
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.listBox1.Items.Add(new ListItem() { DisplayValue = "Run Func1", FuncToInvoke = Func1 });
            this.listBox1.Items.Add(new ListItem() { DisplayValue = "Run Func2", FuncToInvoke = Func2 });
            this.listBox1.Items.Add(new ListItem() { DisplayValue = "Run Func3", FuncToInvoke = Func3 });
        }

        private void Func1()
        {
            MessageBox.Show("Hello World!");
        }

        private void Func2()
        {
            MessageBox.Show("Weather's nice today.");
        }

        private void Func3()
        {
            MessageBox.Show("Goodbye world!");
        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.listBox1.SelectedItem != null)
            {
                ListItem item = this.listBox1.SelectedItem as ListItem;

                if (item != null)
                {
                    item.FuncToInvoke();
                }
            }
        }
    }

    public class ListItem
    {
        public string DisplayValue { get; set; }
        public Action FuncToInvoke { get; set; }

        public override string ToString()
        {
            return this.DisplayValue;
        }
    }
}

Open in new window

0
 
LVL 14

Expert Comment

by:Vel Eous
ID: 39178012
I don't believe that's accurate.

You're correct, I completely forgot about and forgot to check its overloads.  Thanks for pointing that out.

http://msdn.microsoft.com/en-us/library/system.type.getmethod(v=vs.110).aspx
0
 

Author Comment

by:jackjohnson44
ID: 39178040
Thanks guys, one more question though.

How can i split up the step so that i create a list bind the listbox to it?

I don't want to:
this.listBox1.Items.Add(new ListItem() { DisplayValue = "Run Func1", FuncToInvoke = Func1 });
0
 

Author Comment

by:jackjohnson44
ID: 39178090
Thanks, I went with this:
        private Dictionary<string, Action> actions = new Dictionary<string, Action>();

            actions.Add("Log Me In", Login);

             actions[commandName].Invoke();
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…
I've attached the XLSM Excel spreadsheet I used in the video and also text files containing the macros used below. https://filedb.experts-exchange.com/incoming/2017/03_w12/1151775/Permutations.txt https://filedb.experts-exchange.com/incoming/201…

860 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question