C# - 为控制思考循环分配值

时间:2012-01-28 07:37:04

标签: c# winforms loops controls

我有以数字顺序命名的控件。 我想使用循环为这些控件赋值。 下面的代码是我目前正在使用的方式。

txtSalesInvoiceForm_Qty1.Text = (salesInvoice.ItemQty1 == 0) ? string.Empty : salesInvoice.ItemQty1.ToString();
txtSalesInvoiceForm_Qty2.Text = (salesInvoice.ItemQty2 == 0) ? string.Empty : salesInvoice.ItemQty2.ToString();
txtSalesInvoiceForm_Qty3.Text = (salesInvoice.ItemQty3 == 0) ? string.Empty : salesInvoice.ItemQty3.ToString();
txtSalesInvoiceForm_Qty4.Text = (salesInvoice.ItemQty4 == 0) ? string.Empty : salesInvoice.ItemQty4.ToString();
txtSalesInvoiceForm_Qty5.Text = (salesInvoice.ItemQty5 == 0) ? string.Empty : salesInvoice.ItemQty5.ToString();
txtSalesInvoiceForm_Unit1.Text = salesInvoice.Unit1;
txtSalesInvoiceForm_Unit2.Text = salesInvoice.Unit2;
txtSalesInvoiceForm_Unit3.Text = salesInvoice.Unit3;
txtSalesInvoiceForm_Unit4.Text = salesInvoice.Unit4;
txtSalesInvoiceForm_Unit5.Text = salesInvoice.Unit5;
txtSalesInvoiceForm_Particulars1.Text = salesInvoice.Particulars1;
txtSalesInvoiceForm_Particulars2.Text = salesInvoice.Particulars2;
txtSalesInvoiceForm_Particulars3.Text = salesInvoice.Particulars3;
txtSalesInvoiceForm_Particulars4.Text = salesInvoice.Particulars4;
txtSalesInvoiceForm_Particulars5.Text = salesInvoice.Particulars5;

有什么办法吗?

int index = 1;
foreach (SalesInvoiceItem item in salesInvoice.SalesInvoiceItems)
{
    (txtSalesInvoiceForm_Qty + index.ToString()).Text = Value;
    indexer++                        
}

2 个答案:

答案 0 :(得分:3)

Control parent = this.pnlParent; // this must be the immediate parent control

int index = 1;
foreach (SalesInvoiceItem item in salesInvoice.SalesInvoiceItems)
{
    TextBox tb = parent.FindControl( "txtSalesInvoiceForm_Qty" + index++ ) as TextBox;
    tb.Text = Value;       
}

密钥为FindControl(),用于搜索父母的直接子女。我个人认为在大多数情况下这是邋code的代码。

答案 1 :(得分:2)

使用数组而不是那么多命名变量,只需索引到数组中。