I have three TextBoxe1,TextBoxe2 and TextBoxe3 and one main TextBox4 and Button1 when its clicked it will insert TextBox4's value into the clicked (the chosen/selected/clicked one) TextBox. This code Populates all the TextBoxes with the same value.
private void button1_Click(object sender, EventArgs e)
{
TextBox[] array = new TextBox[3] { textBox1, textBox2, textBox3 };
for (int i = 0; i < 3; i++)
{
if (array[i].Focus())
{
array[i].Text = textBox4.Text;
}
}
}
But I want it to take the TextBox4's value and insert into the TextBox2 that I have Clicked on. Like this illu.:
It's better to change the way that you set the value for those TextBox
controls and think about another UI, but anyway, if you like to keep it as is, I'll share an idea to satisfy the requirement which you described in the question.
Define a field in form, TextBox selectedTextBox;
, then handle Enter
event of those 3 TextBox
controls and in the handler set selectedTextBox = (TextBox)sender
. Then in Click
event handler of the button, check if selectedTextBox
is not null, then set selectedTextBox.Text = textBox4.Text;
:
TextBox selectedTextBox;
public Form1()
{
InitializeComponent();
textBox1.Enter += TextBox_Enter;
textBox2.Click += TextBox_Enter;
textBox3.Click += TextBox_Enter;
button1.Click += button1_Click;
}
void TextBox_Enter(object sender, EventArgs e)
{
selectedTextBox = (TextBox)sender;
}
void button1_Click(object sender, EventArgs e)
{
if(selectedTextBox!=null)
selectedTextBox.Text = textBox4.Text;
}
Make sure you don't attach event handler twice, so to attach event handler, use code editor or designer, not both of them.