Percutient
Percutient

Reputation: 43

One Event for all my textBoxes. (VC# Windows Form Application)

I've searched a lot on this site and found similar questions but none of the answers could help me. So I'm going to ask myself. I have this code that doesn't work when I want to put all my textBoxes to the same event, here it is:

private void OnMouseUp(object sender, MouseEventArgs e)
{
  TextBox textBox = (TextBox)sender;
  textBox.SelectionLength = 0;
}

I made this code by looking at other answers on this site to similar questions. I also made this one by combining answers I found here on this site:

private void OnMouseUp(object sender, MouseEventArgs e)
{
  foreach (Control x in this.Controls)
  {
    if (x is TextBox)
     {
      ((TextBox)x).SelectionLength = 0;
     }
  }
}

Which also doesn't work... Can someone please tell me the easiest way to give the same event to all your textBoxes?

Upvotes: 0

Views: 158

Answers (4)

Franreau
Franreau

Reputation: 81

EDIT: If you want to make allt your textbox "unselectable" using a standard .Net way :

foreach (Control x in this.Controls)
    {
        if (x is TextBox)
        {
            ((TextBox)x).Enabled = false;
        }
    }

If it's only to get them unselectable by mouse, then keep the controls attached to your event.

Upvotes: 0

sab669
sab669

Reputation: 4104

Assuming you want every Textbox on your form to have this event:

private void AssignEvent(Control.ControlCollection controls)
{   
    foreach (Control c in controls)
    {
        if (c is Textbox)
            c.MouseUp += OnMouseUp;

        if (c.HasChildren)
            AssignEvent(c.Controls);
    }
}

Call this in your Form_Load like so:

AssignEvent(this.Controls);

This method just loops over every control on your form, and every child control (ie Form has a Groupbox, Groupbox has a Textbox). If it's a Textbox, it assigns the event. If it's not, it'll simply move on to the next one.

Upvotes: 1

Percutient
Percutient

Reputation: 43

I fixed it by doing this:

private void Form1_Load(object sender, EventArgs e)
    {
        foreach (Control x in this.Controls)
        {
            if (x is TextBox)
            {
                ((TextBox)x).MouseUp += SLMethod;
            }
        }
    }

    static void SLMethod(object sender, MouseEventArgs e)
    {
        TextBox textBox = (TextBox)sender;
        textBox.SelectionLength = 0;
    }

What this code is doing is making me unable to select the code within my box with my mouse. Which is what I want. I did not really understand your answers but thank you anyways!

Upvotes: 0

Niels V
Niels V

Reputation: 995

Add textbox1.OnMouseUp+= OnMouseUp in your forms class.

Upvotes: 3

Related Questions