Miguel Flores Miguel Flores - 2 months ago 11
C# Question

How to get string value from combobox to double c#

I'm trying to create an application with C#, in this application I want to select Element1 and Element2, Element 1 and 2 are in a ComboBox, I fill the combobox with this function:

private void agregarItems()
{
comboBox1.DisplayMember = "Text";
comboBox1.ValueMember = "Value";

var items = new[] {
new { Text = "Li", Value = "6.941" },
new { Text = "Mg", Value = "24.305" }
};
comboBox1.DataSource = items;
}


That's ok, then I have a button, when I click this button I want to display the total of the sum of Element1 with Element 2.


For example: E1 = 6.941 and E2 = 6.941 Total = 13.882


What I'm trying is the following code:

private void sum()
{
double val1 = comboBox1.SelectedValue;
double val2 = comboBox2.SelectedValue;

var total = val1 + val2;
}


But I get the following error:


cannot convert from 'object' to 'string'


What I'm doing wrong and how can I solve it?

Answer

Your code it's fine just make this change:

private void sum()
{
     double val1 = Double.Parse(comboBox1.SelectedValue.ToString());
     double val2 = Double.Parse(comboBox2.SelectedValue.ToString());

    var total = val1 + val2;
}

I'll hope this help you