Reducing repetition in vb.net

73 views Asked by At

How can i reduce this ugly block of text? I wanted to use a for loop, but i need to refer to different objects for each iteration of ids .... temperature (i). Also, if i were to rename my objects to LB_Something0, LB_Something1, how could i incorporate that into the for loop?

    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

There are 3 answers

5
Abhitalks On BEST ANSWER

You could do it by naming your controls suffixed with a counter, like:

LBHeater1, LBHeater2...

Then use that counter to find the control. Something like this:

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

Note: Mark the second parameter to Find as True if you want to search all child controls as well. Find returns an array so pick the first one.

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

2
Larry On

Using a array of controls and a loop will help you. However, you have to be very carefull about the order. Maybe using the .NET DataBinding mechanism would help?

Something like this:

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
0
Aprendiendo.NET On

You can use With & End 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