gpt4 book ai didi

c# - 想要在 gridview 的一列中获取相同字符串值的总数

转载 作者:太空宇宙 更新时间:2023-11-03 21:14:16 24 4
gpt4 key购买 nike

gridview 中有一个复选框列,字符串值“P”正在从中被选中。因此,我想计算此列中具有相同“P”值的所有行。我尝试了以下代码:

int sumP = 0;
public void countpresent() //To count all Present Students in the gridview
{
for (int i = 0; i < (dgvAttendance.Rows.Count-1); i++)
{
if (dgvAttendance.Rows[i].Cells["Present"].Value.ToString() == "P")
{
sumP += 1;
}
}
lblPresent.Text = sumP.ToString();
}

它适用于所有字符串“P”,但当它显示值为 null 时,它会抛出异常“对象引用未设置到对象的实例”。在异常详细信息中,它显示“NullReferenceException”。请任何人提出一些帮助

最佳答案

您可能需要在执行操作之前检查 dgv 行是否不为空:

在 C#6 中:

if (dgvAttendance.Rows[i].Cells["Present"].Value?.ToString() == "P")
{
sumP += 1;
}

或者在旧版本中:

if (dgvAttendance.Rows[i].Cells["Present"].Value != null && dgvAttendance.Rows[i].Cells["Present"].Value?.ToString() == "P")
{
sumP += 1;
}

或者实际上,在旧版本中,您可以尝试使用 Convert.ToString,因为它旨在处理 null

 if (Convert.ToString(dgvAttendance.Rows[i].Cells["Present"].Value) == "P")
{
sumP += 1;
}

关于c# - 想要在 gridview 的一列中获取相同字符串值的总数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35527962/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com