Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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();
}

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading