我在ListForm
中有一个C#
问题是,当用户点击列表中的某个学生时,我希望它能够找到平均值,分数和总和
代码如下:
private void listForm1_SelectedIndexChanged(object sender, EventArgs e)
{
txtTotal.Text = listForm1.SelectedItem.ToString();
}
private void Form1_Load(object sender, EventArgs e)
{
listForm1.Items.Add("Hamish overtonne" + "|" + 39 + "|" + 12 + "|" + 85);
listForm1.Items.Add("Claudia Dye" + "|" + 44 + "|" + 56 + "|" + 85);
listForm1.Items.Add("Mike Layne" + "|" + 12 + "|" + 47+ "|" + 28);
}
这就是我现在所拥有的全部
答案 0 :(得分:0)
这是您可以用来执行此操作的代码。请记住将SelectedIndexChanged
事件注册到您的列表中。
还要记住,像我一样使用整数将创建整数,不带小数点。
我已经添加了代码注释来解释这个过程:
private void listForm1_SelectedIndexChanged(object sender, EventArgs e)
{
// Get the value from the selected item
string val = listForm1.GetItemText(listForm1.SelectedItem);
// Split the item's value to a string array according to the pipe char
string[] valArray = val.Split('|');
int sum = 0;
int scores = 0;
// Iterate through all possible values and sum it up,
// while keeping count to how many numbers there are:
for (int i = 1; i < valArray.Length; i++)
{
int num = Convert.ToInt32(valArray[i]);
sum += num;
scores++;
}
// Calculate the average.
// Keep in mind using an integer will create a whole number, without decimal points.
int average = sum / scores;
// Place the average and the sum in textboxes
txtAverage.Text = average.ToString();
txtTotal.Text = sum.ToString();
txtCount.Text = scores.ToString();
}
答案 1 :(得分:-1)
尝试以下代码:
private void listForm1_SelectedIndexChanged(object sender, EventArgs e)
{
// Get the value from the selected item
string val = listForm1.GetItemText(listForm1.SelectedItem);
// Split the item's value to a string array according to the pipe char
string[] valArray = val.Split('|');
int sum = 0;
int scores = 0;
int value=0;
// Iterate through all possible values and sum it up,
// while keeping count to how many numbers there are:
for (int i = 1; i < valArray.Length; i++)
{
int.TryParse(valArray[i], out value);
if(value>0){
int num = value;
sum += num;
scores++;
}
}
// Calculate the average.
// Keep in mind using an integer will create a whole number, without decimal points.
int average = sum / scores;
// Place the average and the sum in textboxes
txtAverage.Text = average.ToString();
txtTotal.Text = sum.ToString();
txtCount.Text = scores.ToString();
}