Can I run multiple controls, but the same method in C #

Example

txtUnitTotalQty.Text = ""; txtPrice.Text = ""; txtUnitPrice.Text = ""; lblTotalvalue.Text = ""; 

To something like

 (txtUnitTotalQty, txtPrice, txtUnitPrice, lblTotalvalue).Text = ""; 
+7
c #
source share
4 answers

You can do it as follows:

 txtUnitTotalQty.Text = txtPrice.Text = txtUnitPrice.Text = lblTotalvalue.Text = string.Empty; 

Or you can write a method for it:

 public void SetText(params TextBox[] controls, string text) { foreach(var ctrl in controls) { ctrl.Text = text; } } 

Using this will:

 SetText(txtUnitTotalQty, txtPrice, txtUnitPrice, lblTotalvalue, string.Empty); 
+9
source share

As .Text is a property of a common control element of a base class, you can iterate over a list:

 new List<Control> { txtUnitTotalQty, txtPrice, txtUnitPrice, lblTotalvalue }.ForEach(c => c.Text = ""); 
+3
source share

Another possible way to write the same thing with a smaller function is

 void ClearAllText(Control con) { foreach (Control c in con.Controls) { if (c is TextBox) ((TextBox)c).Clear(); } } 
+1
source share

You can do something like this:

 foreach (var txt in new[] { txtUnitTotalQty, txtPrice, txtUnitPrice, lblTotalValue} ) { txt.Text = ""; } 
+1
source share

All Articles