Solved

c# store function in list or call function by name

Posted on 2013-05-18
7
408 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
PeopleSoft Has Never Been Easier

PeopleSoft Adoption Made Smooth & Simple!

On-The-Job Training Is made Intuitive & Easy With WalkMe's On-Screen Guidance Tool.  Claim Your Free WalkMe Account Now

 
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

Guide to Performance: Optimization & Monitoring

Nowadays, monitoring is a mixture of tools, systems, and codes—making it a very complex process. And with this complexity, comes variables for failure. Get DZone’s new Guide to Performance to learn how to proactively find these variables and solve them before a disruption occurs.

Question has a verified solution.

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

Suggested Solutions

Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…

734 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