C#-为控制思想循环赋值
本文关键字:循环 赋值 控制 C#- | 更新日期: 2023-09-27 18:21:36
我有按数字顺序命名的控件。我想使用循环为那些控件赋值。下面的代码是我目前使用的方式。
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++
}
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()
,它搜索父级的直属子级。就我个人而言,我认为这在大多数情况下都是草率的代码。
使用一个数组而不是这么多命名变量,只对数组进行索引。