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
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.
You could also use Linq...
Controls.OfType<TextBox>().ToList().ForEach(tb => tb.Text = "");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With