Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

c# store function in list or call function by name

Posted on 2013-05-18
7
Medium Priority
?
412 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 1000 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
URL rewriting in AWS CloudFront

A quick how-to guide to implement with a Lambda function!

 
LVL 75

Accepted Solution

by:
käµfm³d   👽 earned 1000 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

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

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!
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
This course is ideal for IT System Administrators working with VMware vSphere and its associated products in their company infrastructure. This course teaches you how to install and maintain this virtualization technology to store data, prevent vuln…
Want to learn how to record your desktop screen without having to use an outside camera. Click on this video and learn how to use the cool google extension called "Screencastify"! Step 1: Open a new google tab Step 2: Go to the left hand upper corn…

722 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