簡體   English   中英

我可以在C#中運行多個控件但是相同的方法

[英]Can I run multiple control but same method in C#

例如

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

喜歡的東西

(txtUnitTotalQty, txtPrice, txtUnitPrice, lblTotalvalue).Text = "";

你可以這樣做:

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

或者你可以為它編寫一個方法:

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

使用方法是:

SetText(txtUnitTotalQty, txtPrice, txtUnitPrice, lblTotalvalue, string.Empty);

由於.Text是公共基類Control的屬性,因此您可以迭代列表:

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

使用較小函數編寫相同內容的另一種可能方法是

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

你可以這樣做:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM