Search code examples
c#winformsuser-interfacelistviewformatexception

Converting listview subitems to double


I am creating a process scheduling calculator on C# and I created to listviews 1 for the inputs and one for the scheduling itself , however when I started coding the FCFS scheduling part I fail to convert the burst time subitem to double so I can add the waiting time here is some parts of the code and a screenshot to the form

 public void button1_Click(object sender, EventArgs e)
 {
    if (textBox1.Text == "" || textBox2.Text == "" || textBox3.Text == "")
    {
        MessageBox.Show("Insert the required in the boxes");
    }
    else
    {
        ListViewItem Process = new ListViewItem(textBox1.Text);
        Process.SubItems.Add(textBox2.Text);
        Process.SubItems.Add(textBox3.Text);
        Process.SubItems.Add(textBox4.Text);
        listView1.Items.Add(Process);
        textBox1.Text = "";
        textBox2.Text = "";
        textBox3.Text = "";
        textBox4.Text = "";
    }
}

private void button2_Click(object sender, EventArgs e)
{
    double temp = 0;

    //First Come First Served
    if (comboBox1.Text == "FCFS")
    {
        for (int i = 0; i < listView1.Items.Count; i++)
        {
            ListViewItem WaitingTime = new ListViewItem(listView1.Items[i].Text);
            //temp = Convert.ToDouble(listView2.Items[i].SubItems[0]) + Convert.ToDouble(listView2.Items[i + 1].SubItems[0]);
            if (listView2.Items.Contains(WaitingTime))
            {
                WaitingTime.SubItems.Add(temp.ToString());
                listView2.Items.Add(WaitingTime);
            }
            else
            {
                WaitingTime.SubItems.Add(temp.ToString());
                listView2.Items.Add(WaitingTime);
            }
        }
    }

    //SJF Non-preemptive
    if (comboBox1.Text == "SJF non-preemptive")
    {
        for (int i = 0; i < listView1.Items.Count; i++)
        {
            listView2.Items.Add(listView1.Items[i].Text);
        }
    }
}

enter image description here

I tried several times and searched couple forms and all I get is FormatExpection.


Solution

  • Subitems[0] will hold the first subelement, which is the same as the Text of the item, also you cannot convert a ListViewItem.Subitem into a text, you need to use the Text property.

    So you need to use:

    listView2.Items[i].SubItems[1].Text 
    

    In your convert, also I recommend to use Double.TryParse instead of Convert.ToDouble, is faster and will tell you if it was parsed or not.