1

I have controls that are named in numeric sequence. I'd like to assign values those controls using loop. The code below is the way i'm currently using.

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;

Is there any way something like this?

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

2 Answers 2

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;       
}

The key is FindControl(), which searches the immediate children of a parent. Personally I think this is sloppy code in most cases.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks! this's exactly what i wanted! Bu how come i can't use parent.FindControl() ? it says Windows.Form.Controls does not contain a definition of FindControl().
@SiHyungLee - I didn't know you were using Windows Forms (assumed web forms). See msdn.microsoft.com/en-us/library/… for similar functionality.
2

Use an array rather than so many named variables and just index into the array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.