This code is in ASP.NET with C#. A small snippet of that code looks like this:
case 1:
{
txtQty1.Text = decQty.ToString("0.0");
txtDesc1.Text = strDescription;
txtCost1.Text = decCost.ToString("0.00");
txtVAT1.Text = decTax.ToString("0.00");
txtTotal1.Text = decTotal.ToString("0.00");
txtGrossEach1.Text = decGrossEach .ToString( "0.00");
lblCostCodeProfileId1.Text = iCostCodeProfileId.ToString(CultureInfo.InvariantCulture);
SetupCostCentre1(iCostCodeProfileId);
// cost centres should be refreshed using the value of Cost Code Profile
ddlCostCentres1.SelectedValue = iCostCentre.ToString(CultureInfo.InvariantCulture);
if(iCostCentre !=0)
{
RefreshExpenseCodeList1(iCostCentre);
}
ddlCostCentres1.SelectedValue = iCostCentre.ToString(CultureInfo.InvariantCulture);
ddlExpCode1.SelectedValue = iExpenseCode.ToString(CultureInfo.InvariantCulture);
ddlVatRate1.SelectedValue = iVatRate.ToString(CultureInfo.InvariantCulture);
break;
}
case 2:
{
txtQty2.Text = decQty.ToString("0.0");
txtDesc2.Text = strDescription;
txtCost2.Text = decCost.ToString("0.00");
txtVAT2.Text = decTax.ToString("0.00");
txtTotal2.Text = decTotal.ToString("0.00");
txtGrossEach2.Text = decGrossEach.ToString("0.00");
lblCostCodeProfileId2.Text = iCostCodeProfileId.ToString(CultureInfo.InvariantCulture);
SetupCostCentre2(iCostCodeProfileId);
// cost centres should be refreshed using the value of Cost Code Profile
ddlCostCentres2.SelectedValue = iCostCentre.ToString(CultureInfo.InvariantCulture);
if (iCostCentre != 0)
{
RefreshExpenseCodeList2(iCostCentre);
}
ddlCostCentres2.SelectedValue = iCostCentre.ToString(CultureInfo.InvariantCulture);
ddlExpCode2.SelectedValue = iExpenseCode.ToString(CultureInfo.InvariantCulture);
ddlVatRate2.SelectedValue = iVatRate.ToString(CultureInfo.InvariantCulture);
break;
}
Now, the only difference between Case 1 and Case 2 in the above list is in the names of the fields being filled. There is a lot of scope for omission or error here, where what is required is for each set to be treated exactly the same.
Is there any way I can dynamically refer to the fields and write the code only once.
Textboxes are objects as anything else, so you can assign variables to them.
var txtQty = (param == 1) ? txtQty1 : txtQty2;
txtQty.Text = decQty.ToString("0.0");
However it seems that you should have one user control which will hold all you TextBoxes, and put it twice on the page. Put code from this switch to the user control as well.
Method inside user control:
public void FillControls(DataParams p) {
txtQty.Text = p.decQty.ToString("0.0");
txtDesc.Text = p.strDescription;
txtCost.Text = p.decCost.ToString("0.00");
txtVAT.Text = p.decTax.ToString("0.00");
txtTotal.Text = p.decTotal.ToString("0.00");
...
}
And in your page or parent control
var uc = (param == 1) ? userControl1 : userControl2;
uc.FillControls(data);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With