Giovanni
Giovanni

Reputation: 29

How to check if the mouse is in a text box?

The user clicks on a text box. After this he selected an item from a list box and the program put the item name in the text box.

The program must uptate the text of the text box only if the user do this path: Cliks on Text Box -> Selected Item from ListBox

If the user does this: Clicks on Text Box -> Does Something Else -> Selected Item from ListBox the program must not uptade the text of the text box.

How can I do it?

private void TextBox_MouseLeave(object sender, EventArgs e)
{
      mouse_leave = false;
}

private void ListBox_SelectedIndexChanged(object sender, EventArgs e)
{
     if(mouse_leave)
     {
           //Do something..
     }         
}

Upvotes: 1

Views: 855

Answers (2)

Dishant Batra
Dishant Batra

Reputation: 23

You can access the selected item value as shown in the code below:

public partial class Form1 : Form
{
    private bool isUpdated = false;
    public Form1()
    {
        InitializeComponent();
    }

    private void listBox1_SelectedIndexChanged(Object  sender, EventArgs e)
    {
        if (this.isUpdated)
        {
            this.textBox1.Text = ((ListBox)sender).SelectedItem.ToString();
            this.isUpdated = false;
        }

    }

    private void textBox1_Enter(object sender, EventArgs e)
    {
        this.isUpdated = true;
    }
}

Upvotes: 1

Hadi Amini
Hadi Amini

Reputation: 41

If I understood you correctly , you should do this .

  1. define Public variable .

    var selectedTextBox;

  2. when user click on TextBox ,you should save this TextBox name into variable in Step 1.

       private void TextBox_MouseLeave(object sender, EventArgs e)
    {
          selectedTextBox=TextBox.Name ; // Or This.Name;
    }
    
  3. then, when user click on item in listBox, you should take selected value and show in Selected TextBox in Step 2 .

    private void ListBox_SelectedIndexChanged(object sender, EventArgs e) { selectedTextBox.Text = ListBox.SelectedItem.ToString(); }

Upvotes: 0

Related Questions