lost_in_the_source
lost_in_the_source

Reputation: 11237

Read two textBoxes with efficiency

I am writing a program in VB.NET Winforms that takes a Customary Measurement and makes it into Metric System(SI Units). But I need to read what unit the user entered in one box and what unit was entered in the second one. For example the user could enter "Feet" in one box and then "Meters" in another. I need to test this, using a switch but writing it would be too inefficient.

'Not efficient:
Select Case CustomaryUnits.Text
    Case CustomaryUnits.Text Is "Feet" And MetricUnit.Text Is "Meters"
'etc etc etc
End Select

What could I do instead?

Upvotes: 0

Views: 75

Answers (1)

T McKeown
T McKeown

Reputation: 12857

I would do the following:

0) Keep the text box to enter the qty/number of feet/inches/meters etc...
1) Use drop down list instead of text boxes.
2) Instead of just putting text as the items for the drop down create classes and add them as the items. The drop down items will have their .ToString() called to get their Text values for the items.
3) All of these items could inherit a base/abstract class so you could pass the qty value.

For example, your drop down items could be something like this:

I'm a C# person and don't have the time to convert so here is my idea expressed in c# code.

public abstract class MeasureableItem
{

    public string Name { get; private set; }
    public MeasureableItem(string name)
    {
       Name= name;
    }
    public abstract decimal ConvertFrom( MeasureableItem from, decimal qty);
    public override string ToString() { return Name; }
}

You would then define some types:

public class Inches : MeasureableItem
{
    public Inches() : base("Inches") {}
    public override decimal ConvertFrom( MeasureableItem from, decimal qty)
    {
         if ( from is typeof(Feet) )
         {
            return qty * (decimal)12;
         }
         else{
            throw new Exception("Unhandled conversion.");
         }
    }
}

public class Feet  : MeasureableItem
{
    public Feet() : base("Feet") {}

    public override decimal ConvertFrom( MeasureableItem from, decimal qty)
    {
         if ( from is typeof(Inches) )
         {
            return qty / (decimal)12;
         }
         else{
            throw new Exception("Unhandled conversion.");
         }
    }
}

You could obviously add "else if { }" to support more conversions.

To add to the drop down do this:

MeasureableItem inches = new Inches();
MeasureableItem feet = new Feet();

dropDownFrom.Items.Add( inches);
dropDownFrom.Items.Add( feet);

You would have to create a dedicated instance for the "To" dropdown also, I don't believe the controls allow you to share items across multiple controls.

Upvotes: 1

Related Questions