user18305697
user18305697

Reputation: 1

How to pass different values to textboxes by clicking the same button in C# window applications?

Hy I have developed a calculator in C# (window applications). I have two textboxes on the form to get inputs from the user and combobox to select the operation to on the input numbers. And my problem is that when I pressed the 1 button the code is passing 1 to both textboxes. I want to solve this problem like when i click on the textbox1 and then i press the button 1 the code will pass value to only textbox1. And when i click the textbox2 and then by pressing the button 1 the code will have to pass value only to textbox2. Thanks in advance for answering.

Upvotes: 0

Views: 40

Answers (1)

Jiale Xue - MSFT
Jiale Xue - MSFT

Reputation: 3670

Simply add a Bool to determine which textbox the currently selected focus is on.

Add focus event to textbox:

enter image description here

private void textBox1_Enter(object sender, EventArgs e)
        {
            Flag = true;
        }

        private void textBox2_Enter(object sender, EventArgs e)
        {
            Flag = false;
        }

Code:

using System;
using System.Windows.Forms;

namespace WindowsFormsApp2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        public static bool Flag = true;
        private void button1_Click(object sender, EventArgs e)
        {

            if (Flag)
            {
                textBox1.Text += "1";
            }
            else
            {
                textBox2.Text += "1";
            }
        }

        private void textBox1_Enter(object sender, EventArgs e)
        {
            Flag = true;
        }

        private void textBox2_Enter(object sender, EventArgs e)
        {
            Flag = false;
        }
    }
}

Output:

enter image description here

Upvotes: 1

Related Questions