Click here to Skip to main content
16,020,628 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
is there a way to right a logic so that buttons 0 - 9 can run off one piece of code and whe npress button the number appears in the textbox?
Posted
Comments
Sergey Alexandrovich Kryukov 13-Mar-12 18:45pm    
Logic? Are you talking about real hardware pad (which already works), or virtual (simulated by UI)? What kind of UI? What's the problem? It sounds so trivial and straightforward...
--SA
Clifford Nelson 13-Mar-12 19:27pm    
What environment are you using? WinForms, WPF, ASP.NET
stefanere2k9 13-Mar-12 19:33pm    
WinForms

Following the discussion with mark merrens I created a placative example. (just showing the point, no error-handling!)

C#
using System;
using System.Windows.Forms;

namespace OnHandlerForAll
{
    static class Program
    {
        [STAThread]
        static void Main()
        {
            Application.Run(new FormWithButtons());
        }

        public class FormWithButtons : Form
        {
            ListBox listbox = new ListBox() { Dock = DockStyle.Fill };

            public FormWithButtons()
            {
                Controls.Add(listbox);
                for (int i = 0; i < 10; i++)
                {
                    Button button = new Button() { Text = i.ToString(), Tag = i, Dock = DockStyle.Top };
                    // button.Click += new EventHandler(button_Click);
                    button.Click += new EventHandler(button_ClickWithSwitch);
                    Controls.Add(button);
                }
            }

            void button_Click(object sender, EventArgs e)
            {
                Button buttonSender = sender as Button;
                // we don't have to know which number the "button" carries, if there is a new Button we don't have to extend it.
                listbox.Items.Add(buttonSender.Tag); // we need numbers in the ListBox for some reason
            }

            void button_ClickWithSwitch(object sender, EventArgs e)
            {
                Button buttonSender = sender as Button;

                // We have to "know" the cases before, If there is a new Button we have to extend it
                switch (buttonSender.Text)
                {
                    case "0": listbox.Items.Add(0); break; // we need numbers in the ListBox for some reason
                    case "1": listbox.Items.Add(1); break;
                    case "2": listbox.Items.Add(2); break;
                    case "3": listbox.Items.Add(3); break;
                    case "4": listbox.Items.Add(4); break;
                    case "5": listbox.Items.Add(5); break;
                    case "6": listbox.Items.Add(6); break;
                    case "7": listbox.Items.Add(7); break;
                    case "8": listbox.Items.Add(8); break;
                    case "9": listbox.Items.Add(9); break; 
                }
            }
        }
    }
}
 
Share this answer
 
A working hack I have seen in real world implementation was to convert the string on the Buttons "1", "2" to a number in the Click-Handler. I wouldn't do it like that, but use the Tag-Property of the Button like this:

C#
Button button = new Button();
button.Text = "1";
button.Tag = 1;
button.Click += delegate(object obj, EventArgs ea)
{
    Button buttonClicked = obj as Button;
    int iNumberButtonIsRepresenting = (int)  buttonClicked.Tag;
    // ...
};
 
Share this answer
 
Comments
R. Giskard Reventlov 14-Mar-12 12:15pm    
I can't see where this is better than the solution I offered (which is not a 'hack'). If anything, it will lead to a similar amount of code: you still have to handle what you would do with each number. Where is that any better than what I proposed? Have 2 for giving an answer that isn't any better than mine. Have a nice day.
johannesnestler 14-Mar-12 13:12pm    
Thank you for your opinion. I think you didn't get my point - maybe I should have provided an real world example. Think about creating a calculator UI, On Button Click you fill a textbox with the values/operators. The thing you don't want is to specifically react to a special button, but just take the number/operator "on" the button. You are technically right, with your solution u have just one handler... - but not one "function" to handle them all - you have to extend it for each case. I'm not only talking in theory, have a look at this (taken from the code of an visualisation framework) (they did it with the button text, like I mentioned in my answer, - this is what I called a "hack") private void cmdNumber_Click(object sender, System.EventArgs e)
{
numEdit.SendKey(Convert.ToChar(((CommandButton)sender).Text));
}
where numEdit is some kind of Textbox which will later convert the individual "digits" to an number. I think this is what OP is after. Please don't be angry on me - I mentioned your code is not "bad", and never called it a "hack"!
R. Giskard Reventlov 14-Mar-12 14:26pm    
My apologies if you think I'm angry with you: I most certainly am not. I appreciate you taking the time to respond to me and higlight some alternate solutions. Mine was a solution that I thought most closely matched the question - it certainly isn't the only solution so feel free to keep pointing that out. I was only a tad miffed because you marked me down without saying why - no one can learn anything from that. You get my 5 for persevering and sticking to your guns. :thumbsup:
johannesnestler 14-Mar-12 15:48pm    
I'm glad you are not angry :-) Btw - I didn't gave you a bad vote before I explained it - I never do - That was someone else :-) Thank you for your 5 - I love codeproject for it's nice members and fruitful discussions.
Use the CommandArgument and CommandName of the button controls. Give each of the buttons the same CommandName and give each of the buttons a number for the CommandArgument. Very crudely might look like:

C#
protected void btnSubmit_Command(object sender, CommandEventArgs e)
{
	switch (e.CommandArgument)
	{
		case 0:
			// Do something...
			break;
		case ...
	}
}
 
Share this answer
 
Comments
R. Giskard Reventlov 13-Mar-12 19:07pm    
Can whomever marked this down explain why? Show how you would do it different/better???
johannesnestler 14-Mar-12 11:15am    
reason for bad vote: not only asp.net but if you do it like this it wouldn't be better than using different handlers. If you add a new "number" button you'd have to revisit your handler code (and add a new case). Compare that to the common handling I suggest (using Text-property - not so good/flexible, or use Tag-Property - better/flexible) - If I add a new Button (e.g for Hex-Numbers" the handler stays the same. So your code is not "bad" in anyway, it just doesn't solve OP's problem.
R. Giskard Reventlov 14-Mar-12 12:10pm    
I would disagree with you. I answered his exact question with a solution that works with a single event handler.
johannesnestler 14-Mar-12 13:34pm    
I added a new solution to point out the difference between our two aproaches (also showing that we can achieve the same results).
Clifford Nelson 13-Mar-12 19:28pm    
They may have marked you down because you assumed ASP.NET without asking a question about where trying to implement. Your answer could be useless to them.
I am still making a few assumptions when I provide this code. First I am assuming that the text of the buttons will be the number, and second that you want the integer value associated with the button.
public Form1()
{
  InitializeComponent();
}

private void button_Click(object sender, EventArgs e)
{
  Debug.Assert(sender is Button);
  var btn = (Button)sender;
  //Assumes that Button has caption of number
  IsNumeric(btn.Text);
  var number = int.Parse(btn.Text);
  //Whatever you want to do here
}

[Conditional("Debug")]
private void IsNumeric(string value)
{
  int temp;
  Debug.Assert( int.TryParse(value, out temp));
}


I also put in code for debugging. You have to wire up each number button to use the button_Click on the clidk event. That code is in the code behind.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900