此代码在ASP.NET中使用C#。该代码的一小段代码如下:
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;
}
现在,上面列表中案例1和案例2之间的唯一区别在于要填充的字段的名称。这里有很多遗漏或错误的范围,其中要求对每一组进行完全相同的处理。
有什么方法可以动态引用字段并只编写一次代码。
答案 0 :(得分:2)
文本框是其他任何对象,因此您可以为它们分配变量。
var txtQty = (param == 1) ? txtQty1 : txtQty2;
txtQty.Text = decQty.ToString("0.0");
但是,您似乎应该拥有一个用户控件来保存所有TextBox,并将其放在页面上两次。将此switch
中的代码也放到用户控件中。
用户控制中的方法:
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");
...
}
在您的页面或父级控件中
var uc = (param == 1) ? userControl1 : userControl2;
uc.FillControls(data);
答案 1 :(得分:1)
当然,只需将公共代码拉入一个将控件作为参数的方法。
private void SomeMethod( TextBox qty, TextBox desc, TextBox cost, TextBox, vat, etc... )
{
qty.Text = decQty.ToString("0.0");
desc.Text = strDescription;
cost.Text = decCost.ToString("0.00");
vat.Text = decTax.ToString("0.00");
total1.Text = decTotal.ToString("0.00");
grossEach.Text = decGrossEach .ToString( "0.00");
/// etc...
}
然后在你的主叫代码中:
case 1:
SomeMethod( txtQty1, txtDesc1, txtCost1, etc... );
break;
case 2:
SomeMethod( txtQty2, txtDesc2, txtCost2, etc... );
break;