Solved

c# store function in list or call function by name

Posted on 2013-05-18
7
393 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:Tchuki
Tchuki 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:Tchuki
ID: 39177937
The GetMethod function can only reflect on public methods.
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 74

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:Tchuki
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

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

In my previous article (http://www.experts-exchange.com/Programming/Languages/.NET/.NET_Framework_3.x/A_4362-Serialization-in-NET-1.html) we saw the basics of serialization and how types/objects can be serialized to Binary format. In this blog we wi…
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…
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.

760 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

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now