0

what I'm trying to do is to change the text of the "last" lost focussed TxtBox by using a button. I know about the LostFocus method, but what are the actual paramaters that we have to give to that fuction?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.IO;



namespace WindowsFormsApp2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        // this.ActiveControl = textBox2;
    }

        private Control _focusedControl;
        private void button1_Click(object sender, EventArgs e)
        {
            SubmitData();
        }
        private void SubmitData()
        {
            if (_focusedControl != null)
            {
                _focusedControl.Text = "hi";
            }

        }
        private void TextBox2_GotFocus(object sender, EventArgs e)
        {
            MessageBox.Show("Got focus.");
            _focusedControl = (Control)sender;
        }
    }
}

So, what is happening is, no messagebox is popping and the _focusedCOntrol varable doesn't contain the last focus.

GeneNight
  • 35
  • 6
  • 4
    Possible duplicate of [Find out the control with last focus](https://stackoverflow.com/questions/4428100/find-out-the-control-with-last-focus) – JayV Jul 09 '18 at 20:13
  • I saw that post, I understood why is giving that solution but on the GotFocus event even try by changing the text of that TextBox is it not working – GeneNight Jul 09 '18 at 20:34
  • If you are having trouble with a specific implementation, you should post the code you have and we can help you from there. – JayV Jul 09 '18 at 20:37
  • I just updated my post, thank you – GeneNight Jul 09 '18 at 20:42
  • My installation of VS 2017 Community Edition doesn't show `GotFocus` as an event I can handle, I had to wire it up manually with `textBox2.GotFocus += TextBox2_GotFocus;`. Once I did this (and afer disabling the message box), everything worked as expected – JayV Jul 09 '18 at 21:06
  • You are totally right, I had to add the event in the load_form page, could you please explain me why it works like that though? Thank you so much for helping me. – GeneNight Jul 09 '18 at 21:11
  • The `GotFocus` event is defined in the class `System.Windows.Forms.Control` and it has the attribute: `[Browsable(false)]`. That means it won't be shown in the Designer but can be seen with Intellisense and handled as normal. – JayV Jul 09 '18 at 21:28

0 Answers0