Adding a function to one button in an array of buttons - c#

I am trying to make a calculator in C# through code only (Just adding a groupBox and a label in designer).
I have successfully added buttons a coma and a +/- sign.
But now I am running into a problem.
I can assign a function to all of them but
I need to assign a function separately to one of the buttons.
so far I have tried this with one button :
double num = Convert.ToDouble(Answer.Text);
Answer.Text = (-num).ToString();
But since I am working with arrays I have no idea how I can separate one button from another.
Essentially I should be able to do this:
If(Numbers[10].IsPressed)
do this.
but again I don't know the syntaxe's well enough

I dont really know what you want to do... But you might try a 'big' event handler... example:
Button[] buttons;
foreach(var button in buttons)
{
button.Click += MyHandler;
}
// method1
private void MyHandler(object sender, EventArgs e)
{
if(sender == buttons[0])
// Do something...
else if(sender == buttons[1])
// do something else...
else if(sender == buttons[2])
// and so on...
}
// method2
private void MyHandler(object sender, EventArgs e)
{
var button = (Button)sender;
switch(button.Text)
{
case "+":
case "1":
case "2":
// and so on...
}
}

Another good approach is having own handler for every button. Usualy Visual Studio will generate own click handler when you double click button in the designer.
private void ButtonPlus_Click(object sender, EventArgs e)
{
// Do something when "+" pressed
}
private void ButtonMinus_Click(object sender, EventArgs e)
{
// Do something when "-" pressed
}
You can manually add event handlers to the buttons in constructor (in case you used Visual Studio for generating it - Visual Studio will automatically add generated event handler to the button)
this.ButtonPlus.Click += ButtonPlus_Click;
this.ButtonMinus.Click += ButtonMinus_Click;
With approach above you will have own functions for every operations, which can help to maintain your code base little bid easily/faster.
However if you want to use only one event handler for all buttons, then you can use Button.Tag property.
Create method for every operation you have
private void ExecutePlus()
{
// Do something when "+" pressed
}
private void ExecuteMinus()
{
// Do something when "+" pressed
}
Then in constructor save all operations in the .Tag property of correspondent button.
this.ButtonPlus.Tag = ExecutePlus;
this.ButtonMinus.Tag = ExecuteMinus;
// add "general" event handler
var buttons = new[] { this.ButtonPlus, this.ButtonMinus };
foreach(var button in buttons)
{
button.Click += Button_Click;
}
Then create "general" click handler
private void Button_Click(object sender, EventArgs e)
{
var button = (Button)sender;
Action execute = (Action)button.Tag;
execute();
}
You will still have separated method for every operation, but only one event handler for all buttons

Related

many button in windows form with same event, in event i need name of button that selected

i have 46 button in form and all of them to same work just diffrent in value.
mean button1 plus 1 to sum , button2 plus 2 to sum ...
is there a way to understand which one of buttons are pressed to get it Text
private void button1_Click(object sender, EventArgs e)
{
// call a function with this button TEXt
// if button 1 selected -> func("1")
// if button 2 selected -> func("2")
}
is there any way do it ?
sender returns your button.So you can get the button like
Button clicked = (Button)sender;
In specifying the buttons, you can check that sender button's Text or you can give them Tag and check them. You said text, so
Button clicked = (Button)sender;
func(clicked?.Text);
should work.
Button clickedButton = sender as Button;
if (clickedButton != null)
{
button.Name....
}
The most straightforward solution is to create for each button an event_click (so button1_Click, button2_Click etc. Better to name the buttons appropriate.
Than from within each event handler, call the same function to add the number to the sum e.g.:
private void button1_Click(object sender, EventArgs e)
{
add(1);
}
private void button2_Click(object sender, EventArgs e)
{
add(2);
}
// Same for other event handlers.
private void add(int number)
{
sum += number;
}
You can link all your event handlers and then use the Name property to decide which button was clicked.
this.button1.Click += new System.EventHandler(this.button1_Click);
this.button2.Click += this.button1_Click;
private void button1_Click(object sender, EventArgs e)
{
var btn = sender as Button;
switch(btn.Name.ToLower())
{
case "button1":
MessageBox.Show("Add 1");
break;
case "button2":
MessageBox.Show("Add 2");
break;
default:
MessageBox.Show("Button not found");
break;
}
}

How to output to a TexBox directly using RadioButtons and CheckBoxes without clicking Buttons

I want to know how to output to a TextBox as soon as a user has clicked on a series of RadioButtons and clicked the CheckBox(es) which are found inside various GroupBoxes on the Form.
Any help will be really appreciated, in case this question has already been answered in the past let me know I have search for it but could not find anything like this.
Sample Form layout:
I am no good at chasing the pictures and especially code as picture doesn't help anyone. Anyway next time please don't do that.
First, for all of your radio and checkboxes (radChocolate, radVanilla, ... radSmall, ..., chkChocoChips, ...) double click and fill Checked event such as:
private void radChocolate_CheckedChanged(object sender, EventArgs e)
{
CalculatePrice();
}
private void radVanilla_CheckedChanged(object sender, EventArgs e)
{
CalculatePrice();
}
// Do the same for other radio and checkboxes
Then add the CalculatePrice code as such (prices are arbitrary):
private void CalculatePrice()
{
decimal price = 0M;
if (radChocolate.Checked) price += 75M;
if (radVanilla.Checked) price += 65M;
if (radStrawberry.Checked) price += 55M;
if (radSmall.Checked) price += 20M;
if (radLarge.Checked) price += 30M;
if (chkChocoChips.Checked) price += 5M;
if (chkCookieCandy.Checked) price += 4M;
if (chkNuts.Checked) price += 3M;
if (chkFreshFruits.Checked) price += 2M;
txtPrice.Text = price.ToString("C");
}
This would do what you wanted to.
You either need to create an event handler for each radio button, or create a single event handler for all the radio buttons. It would depend on what you are trying to accomplish. For the radio button you would want to subscribe to the CheckedChanged event. Then inside this event you can change the text box.
private void radioButtonChangeText_CheckedChanged(object sender, EventArgs e)
{
//Code here to change text box or call sub
textBox.Text = "Hello world";
}
Based upon your link, you can create one event handler and bind it to all the events. (Link explaining binding)
So, every time any value is changed in your form, only one function gets called.
Then, check the values of every component present in your form and calculate value of your textbox.
Right click on a radio button and the go to properties, there click on "events" (that lightning sign). There is an event there called "CheckedChanged". Double click on the cell next to it to generate the event method.
it will generate a code like this,
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
MessageBox.Show("hi there");
}
you should be able to put any thing you want in there. Assuming you want to show hide the TextBox, you can do it in there.
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
setCheckBoxValue();
}
private void radioButton2_CheckedChanged(object sender, EventArgs e)
{
setCheckBoxValue();
}
private void setCheckBoxValue()
{
int finalPrice = 0;
if (radioButton1.Checked == true)
{
finalPrice = finalPrice + 75;
}
else if (radioButton2.Checked == true)
{
finalPrice = finalPrice + 87;
}
textBox1.Text = finalPrice.ToString("C");
}

how to generate a SelectionRangeChanged Event Programatically ChartControl WinForms

want to create a selectionRangeChanged event programatically not really getting how to do it
private void btn_10D_Click(object sender, EventArgs e)
{
double varRange = 10;
double var_Sel1 = DatesX[0].ToOADate();
Chart1.ChartAreas["ChartArea1"].CursorX.IsUserEnabled = true;
Chart1.ChartAreas["ChartArea1"].CursorX.IsUserSelectionEnabled = true;
Chart1.ChartAreas["ChartArea1"].CursorX.SelectionColor = Color.LightGray;
Chart1.ChartAreas["ChartArea1"].CursorX.SelectionStart = var_Sel1;
Chart1.ChartAreas["ChartArea1"].CursorX.SelectionEnd = varRange + var_Sel1;
Chart1.ChartAreas["ChartArea1"].CursorX.Position = varRange + var_Sel1;
Chart1.SelectionRangeChanged += new EventHandler<CursorEventArgs>(Chart1_SelectionRangeChanged);
}
void Chart1_SelectionRangeChanged(object sender, CursorEventArgs e)
{
throw new NotImplementedException();
}
thank you
For all events in C# is true that if class creator did not make extra effort to allow event firing form outside of class it is impossible to fire them.
According to MSDN
Chart.SelectionRangeChanged event Occurs when the selection start position or end position is changed.
But from my tests I can see that it is fired only if it is changed by user not program.
If I understand your intention correctly you want to handle those small buttons under your chart and btn_10D_Click method is a click handler for one of them. Try to move this line
Chart1.SelectionRangeChanged += new EventHandler<CursorEventArgs>(Chart1_SelectionRangeChanged);
to your constructor and ensure it is called once (remove it form other handlers). This will ensure your code is executed when user changes selection. If you want to execute same code for your button you should simply extract handler contents to method and call it form button click handler.
void Chart1_SelectionRangeChanged(object sender, CursorEventArgs e)
{
DoSomething(/*some arguments if you need them*/);
}
private void btn_10D_Click(object sender, EventArgs e)
{
\\your code
DoSomething();
}

button should refer to itself in C#

Assuming there are buttons with all the letters from the alphabet set as Text.
I want to call a function in these buttons and use this letter as argument.
Can I use the same piece of code for each button in some way?
something like
functionname(this.Text);
Problem is, that "this" referrs to the Form and not to the specific button.
In most event mechanisms you can obtain the source of the event; in classic win forms vents this is typically called "sender". You can cast the sender to what you know it is, or some common base-type. For example:
void SomeEventHandler(object sender, SomeEventArgs e) {
string text = ((Control)sender).Text;
// ...
}
Hence with this a single event-handler can handle all the buttons.
This may vary subtly between infrastructure / tools (WCF, XNA etc) but fundamentally should remain similar.
Try an event handler like this:
protected button1_click(sender as object, e as EventArgs) {
var button1 = (Button) sender;
if (button1.Text == "A") {
//for example
}
}
You will then need to add the event handler, either in "on load" using AddHandler... or if it's an Asp.net page you can use the onClick="button1_click" attribute.
For a more specific answer, I would need some more details.
You could use the same event handler for every button on the form:
private void Form_Load(object sender, System.EventArgs e)
{
foreach (var btn in this.Controls.OfType<Button>())
{
btn.Click += AllButtonClick;
}
}
private void AllButtonClick(Object sender, EventArgs e)
{
Button btn = (Button)sender;
String buttonText = btn.Text;
}

Buttons in a Visual Studios form application

Sorry if this is a dumb question, I'm taking an intro to programming class and need a bit of help with this project I'm working on.
I'm trying to write an application that has about 30 buttons. One common thing I want is for all the buttons to turn yellow when clicked. If they're clicked a second time, they change back to the default color. right now I use the code:
private void btn_1_Click(object sender, EventArgs e)
{
btn_1.BackColor = Color.Yellow;
}
But that only turns the buttons yellow, I can't turn them "off" by clicking it a second time.
Also, when I'm creating these button events in VS2010, I end up with 30 different event handlers for each button..Is there a way to get them all to do the same thing without having to write all the repetitive code?
I'm guessing that I would have to write my own buttons class? How would I go about doing that? Do i need to create a class library which inherits Buttons?
Sorry for the noob questions. THanks
If every button has a specific action that needs to be performed, then yes, you need to have a click handler for each; however, you can encapsulate the common behavior in a single method.
For example:
private void btn_1_Click(object sender, EventArgs e)
{
ToggleColor((Button)sender);
//rest of the code specific to this button
}
private void ToggleColor (Button button)
{
if(button.Color==Color.Yellow;
button.Color=Color.Black;
else
button.Color=Color.Yellow;
}
Note that above code is not tested.
Now, if all the buttons do the same thing, you can just set the on click handlers for all of them to be btn_1_Click; for example.
private void btn_1_Click(object sender, EventArgs e)
{
if (btn_1.BackColor != Color.Yellow)
{
btn_1.BackColor = Color.Yellow
}
else
{
btn_1.BackColor = Color.Control;
}
}
this is switching default and yellow
If all buttons do the exact same thing you can assign the same event handler to all buttons (instead of btn_1_Click, btn_2_Click etc... you'd have btton_click) - you can select this handler in the properties of each button.
You don't have to write your own class. You can simply assign all your buttons to the same event handler, like this:
button1.Click += new EventHandler(myEventHandler);
button2.Click += new EventHandler(myEventHandler);
button3.Click += new EventHandler(myEventHandler);
button4.Click += new EventHandler(myEventHandler);
Just keep in mind that your event handler has this signature:
private void myEventHandler(object sender, EventArgs e)
By doing that, all your buttons, when clicked, will trigger the same method.
Now to control the color, what you can do is create a simple property on your form which would hold the last color applied. It could be an enum, then you could simply check its value and apply the other one to the buttons, like this:
// Declare your enum:
private enum Colors { Yellow, Default }
private Colors ActualColor = Colors.Default;
// Write your custom event handler:
private void myEventHandler(object sender, EventArgs e)
{
if (ActualColor == Colors.Default)
{
// Apply yellow to buttons
ActualColor = Colors.Yellow;
}
else
{
// Apply default
ActualColor = Colors.Default;
}
}
In order to keep track whether it is the 'second time' you press the button, you should declare a variable OUTSIDE the method, which indicates whether you already pressed the button or not.
For example:
public bool IsButtonYellow;
private void btn_1_Click(object sender, EventArgs e) {
if(!IsButtonYellow) {
btn.BackColor = Color.Yellow;
IsButtonYellow = true;
}
else {
btn.BackColor = Control.DefaultBackColor;
IsButtonYellow = false;
}
}
Yes:
Create your own button class
Inherit from Button
Implement the handler in your button class and you're done
You can do something simple like this:
public class MyButton : Button
{
private bool _buttonState;
protected override void OnClick(EventArgs e)
{
base.OnClick(e);
if (_buttonState)
{
BackColor = Color.Yellow;
}
else
{
BackColor = Color.White;
}
}
}
Then in your code you can just create as many of these "MyButton" objects as you need, with no code repetition.
To make all buttons use the same event handler in VS2010:
Click once on a button to select it.
In the “properties” window: click on the “lightning” (=events).
Paste the first button’s event name (btn_1_Click) next to “Click”.
Do the same for every button.
As for changing the color:
See answer by killie01.
Good luck.

Categories

Resources