Strongbad2143
Strongbad2143

Reputation: 35

Min and max button and label

I'm trying to build a exam grader using C#. I'm new to this and don't know very much. What code would I use to add min and max buttons and to add a label stating whether it's a min or max?

private void btnAdd_Click(object sender, EventArgs e)
{
    int points;
    try
    {
        points = int.Parse(txtPoints.Text);
        lstPoints.Items.Add(points);
        txtPoints.Clear();
        txtPoints.Focus();
        if (lstPoints.Items.Count == 12)
        {
            txtPoints.Enabled = false;
            btnAdd.Enabled = false;
        }
        if (lblResult.Text != "")
        {
            lblResult.Text = "";
        }
    }
    catch
    {
        MessageBox.Show("Please enter only whole numbers");
        txtPoints.Clear();
        txtPoints.Focus();
    }
}

private void btnAvg_Click(object sender, EventArgs e)
{     
    double total = 0;
    for (int i = 0; i < lstPoints.Items.Count; i++)
    {
        total += (int)lstPoints.Items[i];
    }
    total /= lstPoints.Items.Count;
    lblResult.Text = total.ToString(); 
}

private void btnClear_Click(object sender, EventArgs e)
{
    lstPoints.Items.Clear();
    txtPoints.Enabled = true;
    btnAdd.Enabled = true;
}
}
}

Upvotes: 0

Views: 294

Answers (2)

NeverHopeless
NeverHopeless

Reputation: 11233

There are two possiblities as I see:

1) When you are writing this:

lstPoints.Items.Add(points);

Instead of adding to List(Of Integer) use SortedList. So the list will always have the sorted result sets.

2) Use Array.Sort() to sort the records.

Once you have sorted records the first one is the minimum and the last one is the maximum (Assuming sorted in ascending order).

Take out two buttons and placed on the form, set Text Property from property window to Min and Max respectively and in event handler handle the Click event and pick the relevant resultset from lstPoints array.

Hope it helps!

Upvotes: 0

T.A.P
T.A.P

Reputation: 69

hope this works

private void getMax()
{
   int max=0;
   for (int i = 0; i < lstPoints.Items.Count; i++)
        {
             if(max<(int)lstPoints.Items[i])
                 {
                     max=(int)lstPoints.Items[i];
                 }
        }

        lblResult.Text = max.ToString(); 
        }

}

private void getMin()
{
   int min=(int)lstPoints.Items[0];
   for (int i = 1; i < lstPoints.Items.Count; i++)
        {
             if(min>(int)lstPoints.Items[i])
                 {
                     min=(int)lstPoints.Items[i];
                 }
        }

        lblResult.Text = min.ToString(); 
        }

}

Upvotes: 1

Related Questions