Solved

c# store function in list or call function by name

Posted on 2013-05-18
7
411 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Is Your Team Achieving Their Full Potential?

74% of employees feel they are not achieving their full potential. With Linux Academy, not only will you strengthen your team's core competencies but also their knowledge of of the newest IT topics.

With new material every week, we'll make sure that you stay ahead of the game.

 
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

Salesforce Has Never Been Easier

Improve and reinforce salesforce training & adoption using WalkMe's digital adoption platform. Start saving on costly employee training by creating fast intuitive Walk-Thrus for Salesforce. Claim your Free Account Now

Question has a verified solution.

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

We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
This is my first video review of Microsoft Bookings, I will be doing a part two with a bit more information, but wanted to get this out to you folks.
This tutorial will teach you the special effect of super speed similar to the fictional character Wally West aka "The Flash" After Shake : http://www.videocopilot.net/presets/after_shake/ All lightning effects with instructions : http://www.mediaf…

632 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