Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I run multiple control but same method in C#

Tags:

c#

For Example

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

To something like

(txtUnitTotalQty, txtPrice, txtUnitPrice, lblTotalvalue).Text = "";
like image 685
Polamin Singhasuwich Avatar asked Jan 27 '16 08:01

Polamin Singhasuwich


4 Answers

You can do it like this:

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

Or you could write a method for it:

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

Usage of this would be:

SetText(txtUnitTotalQty, txtPrice, txtUnitPrice, lblTotalvalue, string.Empty);
like image 172
Simon Karlsson Avatar answered Nov 20 '22 10:11

Simon Karlsson


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

new List<Control> { txtUnitTotalQty, txtPrice, txtUnitPrice, lblTotalvalue }.ForEach(c => c.Text = "");
like image 37
Richard Avatar answered Nov 20 '22 08:11

Richard


You can do something like this:

foreach (var txt in new[] { txtUnitTotalQty, txtPrice, txtUnitPrice, lblTotalValue} )
{
    txt.Text = "";
}
like image 29
Ross Presser Avatar answered Nov 20 '22 08:11

Ross Presser


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();
    }
}
like image 1
Mohit S Avatar answered Nov 20 '22 10:11

Mohit S