在列表视图中计算最终成绩

时间:2015-09-11 15:53:27

标签: c# listview

这是我到目前为止所做的所有代码。系统有一个列表视图,其列标题为:

subject name | 1st | 2nd | 3rd | 4th | Final Grades

如果第1列到第4列包含值,它将计算学生的最终成绩。 sum(1st to 4th)/ 4 * 50 + 50.如果其中一列没有值,则会提示用户,不会计算最终成绩。

我很困惑如何从第1到第4获得所有listview值,然后自动计算最终成绩。

提供帮助

private void button1_Click(object sender, EventArgs e)
{
    flag = false;

    if (txt_numValue.Text != "")
    {
        char[] entereddata = txt_numValue.Text.ToCharArray();

        foreach (char aChar in entereddata.AsEnumerable())
        {
            if (!Char.IsDigit(aChar))
            {
                MessageBox.Show("Please enter only numbers.", "In the field Numeric Value");
                flag = true;
                break;
            }
        }
    }
    else if (txt_numValue.Text == "")
    {
        MessageBox.Show("Please do not leave the field, 'Numeric Value', blank.", "Attention!");
        flag = true;
    }

    if (flag == false)
    {
        string period = txt_gradingPeriod.Text;
        string numeric = txt_numValue.Text;
        int cell = 0;

        if (period == "1st") { cell = 1; }
        else if (period == "2nd") { cell = 2; }
        else if (period == "3rd") { cell = 3; }
        else if (period == "4th") { cell = 4; }

        foreach (ColumnHeader header in listView1.Columns)
        {
            if (header.Text == period)
            {
                listView1.Items[0].SubItems[cell].Text = numeric;
                break;
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

获得列表视图中的所有数据后,您可以执行以下操作,

  int sum = 0;           
        foreach (ListViewItem v in listView1.Items)
        {
            bool hasBlank = false;
            for (int i = 0; i < v.SubItems.Count;i++ )
            {
                if (v.SubItems[i].Text == null || v.SubItems[i].Text == string.Empty)
                {
                    //code                      
                    hasBlank = true;
                    break;                        
                }
                else
                {
                    sum += Convert.ToInt16(v.SubItems[i].Text);
                }
            }
            if (!hasBlank)
            {
                string grade="something";
                //formula to calculate grade based on sum.set the result to string grade
                v.SubItems[4].Text = grade;                   
            }
            else
            {
                v.SubItems[4].Text = "has blank";
            }
            sum = 0;
        }

如果所有值都存在,则填写成绩,否则显示空白值。