Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this work with textboxes in win forms

I am learning C#, for my school homeworks. I suddenly try to do something and I thought, I am going to get a bug in the below code

  private void ClearControls()
        {
            this.textBox1 .Text = "";
            this.textBox1 = this.textBox2 = this.textBox3 = this.textBox4;
        }

Wow...it works better what I expected and it cleared all my text boxes in the form , and before this, I was doing like

textBox1 .Text = "";
textBox2 .Text = "";

and so on till some twenty text boxes in a form (this is the method , my teacher told me and all my classmates follow this :( )..

which one is correct, and why the first one works good and how the default attribute assigned to a textbox is always text and not name or tabindex or someother ones ?

if the question is not clear or a little mess, please tell and I will try change it.

Thanks for taking time to clear my doubts :D

like image 454
Marie Curie Avatar asked Aug 31 '26 15:08

Marie Curie


2 Answers

Not quite. This line sets each reference equal to textBox4, which is not what you want. Now these four references all point to the same thing.

this.textBox1 = this.textBox2 = this.textBox3 = this.textBox4

What you wanted was this:

this.textBox1.Text = this.textBox2.Text = this.textBox3.Text = this.textBox4.Text = ""

However, that is a maintenance headache. Create a UserControl for this stuff or at least maintain a collection of TextBox objects that you can iterate through to set common properties instead of adding a new line for every text box.

like image 91
Ed S. Avatar answered Sep 03 '26 04:09

Ed S.


You could also use Linq...

Controls.OfType<TextBox>().ToList().ForEach(tb => tb.Text = "");
like image 42
Tim Jarvis Avatar answered Sep 03 '26 04:09

Tim Jarvis