The question is not very specific, but has been clarified in the comments.
Your real need would be to convert units by changing the value of the combobox.
Based on the last code, I made the following code, which only includes 3 units, but it has support for adding as many as needed.
Instead of defining the units as a string, we can define them as an enumerable:
public enum PressUnit
{
[Description("Atm")]
Atm = 1,
[Description("Psi")]
Psi = 2,
[Description("Kpa")]
Kpa = 3
}
Class itself, which performs the conversion calculation and has a dictionary with values indexed by unit atm
:
public class Press
{
public Press()
{
Valor = 1;
Unidade = PressUnit.Atm;
}
public PressUnit Unidade { get; private set; }
public decimal Valor { get; private set; }
public void SetValor(decimal _valor, PressUnit _unidade)
{
this.Unidade = _unidade;
this.Valor = _valor;
}
public void SetValor(decimal _valor)
{
this.Valor = _valor;
}
public bool ConvertTo(PressUnit _unidade)
{
decimal c = 0;
if (TabelaAtm.TryGetValue(this.Unidade, out c))
{
decimal atm = this.Valor / c;
decimal d = 0;
if (TabelaAtm.TryGetValue(_unidade, out d))
{
this.Unidade = _unidade;
this.Valor = atm * d;
return true;
}
else
return false;
}
else return false;
}
public static Dictionary<PressUnit, decimal> TabelaAtm = new Dictionary<PressUnit, decimal>()
{
{PressUnit.Atm,1},
{PressUnit.Psi,(decimal)14.6959},
{PressUnit.Kpa,(decimal)101.325}
};
}
To use the enum description attribute more easily, I use this extension method:
static class Extension
{
public static string GetEnumDescription<TEnum>(this TEnum item)
{
DescriptionAttribute x = item.GetType().GetField(item.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false)
.Cast<DescriptionAttribute>().FirstOrDefault();
return x == null ? String.Empty : x.Description;
}
}
Usage:
Form1.cs
public partial class Form1 : Form
{
private Press objPress;
public Form1()
{
InitializeComponent();
objPress = new Press();
//comboBox1.DataSource = Enum.GetValues(typeof(PressUnit));
GetComboUnidades();
}
private void GetComboUnidades()
{
comboBox1.DisplayMember = "Description";
comboBox1.ValueMember = "Value";
comboBox1.DataSource = Enum.GetValues(typeof(PressUnit))
.Cast<Enum>()
.Select(value => new
{
Description = value.GetEnumDescription(),
value
})
.OrderBy(item => item.value)
.ToList();
}
private void Form1_Load(object sender, EventArgs e)
{
textBox1.Text = "0";
}
private void comboBox1_SelectedValueChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedValue != null)
{
objPress.ConvertTo((PressUnit)comboBox1.SelectedValue);
textBox1.Text = objPress.Valor.ToString("N3");
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (!String.IsNullOrEmpty(textBox1.Text) && comboBox1.SelectedValue != null)
{
objPress.SetValor(Convert.ToDecimal(textBox1.Text), (PressUnit)comboBox1.SelectedValue);
}
}
}
Result:
I hope it helps.