减少vb.net中的重复

时间:2014-11-20 07:04:26

标签: vb.net .net-1.1

如何减少这个难看的文本块?我想使用for循环,但我需要为id的每次迭代引用不同的对象.... temperature(i)。另外,如果我要将我的对象重命名为LB_Something0,LB_Something1,我怎么能将它合并到for循环中呢?

    LB_NeedleHeater.Text = IDS.Devices.Thermal.FrmThermal.Temperature(0)
    FrmProduction.Needle.Text = IDS.Devices.Thermal.FrmThermal.Temperature(0)

    LB_SyrHeater.Text = IDS.Devices.Thermal.FrmThermal.Temperature(1)
    FrmProduction.Syringe.Text = IDS.Devices.Thermal.FrmThermal.Temperature(1)

    LB_PreHeater.Text = IDS.Devices.Thermal.FrmThermal.Temperature(2)
    FrmProduction.Station1.Text = IDS.Devices.Thermal.FrmThermal.Temperature(2)

    LB_DispHeater.Text = IDS.Devices.Thermal.FrmThermal.Temperature(3)
    FrmProduction.Station2.Text = IDS.Devices.Thermal.FrmThermal.Temperature(3)

    LB_PostHeater.Text = IDS.Devices.Thermal.FrmThermal.Temperature(4)
    FrmProduction.Station3.Text = IDS.Devices.Thermal.FrmThermal.Temperature(4)

3 个答案:

答案 0 :(得分:1)

您可以通过命名后缀为计数器的控件来实现,例如:

  

LBHeater1,LBHeater2 ......

然后使用该计数器查找控件。像这样:

For i = 0 to IDS.Devices.Thermal.FrmThermal.Temperature.Length - 1
    Me.Controls.Find("LBHeater" & i+1, False)(0).Text = IDS.Devices.Thermal.FrmThermal.Temperature(i)
Next

注意:如果您还想搜索所有子控件,请将Find的第二个参数标记为TrueFind返回一个数组,因此选择第一个数组。

参考http://msdn.microsoft.com/en-us/library/system.windows.forms.control.controlcollection.find(v=vs.100).aspx

答案 1 :(得分:0)

使用控件数组和循环将对您有所帮助。但是,您必须非常小心订单。也许使用.NET DataBinding机制会有帮助吗?

这样的事情:

Dim ctl1 As Control() = {LB_NeedleHeater, LB_SyrHeater, LB_PreHeater, ...}
Dim ctl2 As Control() = {FrmProduction.Needle, FrmProduction.Syringe, FrmProduction.Station1, ...}

For i = 0 to 4
    Dim Temp = IDS.Devices.Thermal.FrmThermal.Temperature(i)
    ctl1[i].Text = Temp
    ctl2[i].Text = Temp
Next

答案 2 :(得分:0)

你可以使用With&结束于:

With IDS.Devices.Thermal.FrmThermal
    LB_NeedleHeater.Text = .Temperature(0)
    FrmProduction.Needle.Text = .Temperature(0)

    LB_SyrHeater.Text = .Temperature(1)
    FrmProduction.Syringe.Text = .Temperature(1)

    LB_PreHeater.Text = .Temperature(2)
    FrmProduction.Station1.Text = .Temperature(2)

    LB_DispHeater.Text = .Temperature(3)
    FrmProduction.Station2.Text = .Temperature(3)

    LB_PostHeater.Text = .Temperature(4)
    FrmProduction.Station3.Text = .Temperature(4)
End With