Home > Net >  Invalid cast error occurs in calculating elements in the listbox
Invalid cast error occurs in calculating elements in the listbox

Time:02-20

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

CodePudding user response:

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);
  • Related