HappyBono
HappyBono

Reputation: 36

Invalid cast error occurs in calculating elements in the listbox

I am trying to calculate the median value from Listbox data in C#. However, occurs invalid cast exception occurs in foreach statement as below (in bold) :

foreach (string item in ListBox1.Items)

can anyone help me how to fix this error? will be highly appreciated.

Thank you.

System.InvalidCastException: Unable to cast object of type 'System.Int32' to type 'System.String'

private void calcButton_Click(object sender, EventArgs e)
{
    medianList.Clear();
    ListBox2.Items.Clear();

    if (sourceList.Count == 0)
    {
        double tInt;
        foreach (string item in ListBox1.Items)
        {
            if (double.TryParse(item, out tInt) == true)
                sourceList.Add(tInt);
        }
    }

    if (ListBox1.Items.Count > 0)
    {
        if (RadioButton1.Checked)
            MiddleMedian();
        else
            AllMedian();
    }
    else
        return;

    DisplayResults();
    sourceList.Clear();
}

Upvotes: 0

Views: 36

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460018

Well, isn't the error message meaningful?

Unable to cast object of type 'System.Int32' to type 'System.String'

foreach (string item in ListBox1.Items)

So you have added integers to the ListBox1. Then this fixes it:

foreach (int tInt in ListBox1.Items)
    sourceList.Add(tInt);

Upvotes: 1

Related Questions