Let's get down to the truth. Let's talk about how to dynamically register button events.
First, we need to set a variable to obtain the value of clicking a number button to calculate the final result by clicking the "=" button in the event. Below is a piece of code I wrote at the beginning:
Copy codeThe Code is as follows:
Public double? Value1 = null; // obtain the value before the operator
Public double? Value2 = null; // obtain the value before the operator
Public type caltype = type. none; // obtain the operator
Private void btnvalue1_Click (object sender, EventArgs e)
{
If (value1 = null)
{
Value1 = Convert. ToDouble (btnvalue1.Text );
}
Else
{
Value2 = Convert. ToDouble (btnvalue1.Text );
}
This.txt value. Text = btnvalue1.Text;
} "1" button click event
There are a total of ten such numeric button click events
Do you think this writing is very troublesome, so you have a button to register the event. The following is the code below:
Copy codeThe Code is as follows:
Public double? Value1 = null; // obtain the value before the operator
Public double? Value2 = null; // obtain the value after the operator
Public type caltype = type. none; // obtain the operator
Private void Form1_Load (object sender, EventArgs e)
{
Btnvalue0.Click + = new EventHandler (btnvalue_Click );
Btnvalue1.Click + = new EventHandler (btnvalue_Click );
Btnvalue2.Click + = new EventHandler (btnvalue_Click );
Btnvalue3.Click + = new EventHandler (btnvalue_Click );
Btnvalue4.Click + = new EventHandler (btnvalue_Click );
Btnvalue5.Click + = new EventHandler (btnvalue_Click );
Btnvalue6.Click + = new EventHandler (btnvalue_Click );
Btnvalue7.Click + = new EventHandler (btnvalue_Click );
Btnvalue8.Click + = new EventHandler (btnvalue_Click );
Btnvalue9.Click + = new EventHandler (btnvalue_Click );
// Click the button control event through EventHandler
Bind to btnvalue_Click to dynamically register button events
}
Private void btnvalue_Click (object sender, EventArgs e)
{
Button btn = (Button) sender;
// Instantiate the button to get the value of the currently clicked button
If (value1 = null)
{
Value1 = Convert. ToDouble (btn. Text );
}
Else
{
Value2 = Convert. ToDouble (btn. Text );
}
This.txt value. Text = btn. Text;
}
Is it much easier to perceive than before ..... (If you want source code, please contact me QQ: 342468914)