出现计数dataGridCells值

本文关键字:dataGridCells | 更新日期: 2023-09-27 17:59:23

我想知道dataGridRows.Cells[1]中有多少0。我将此代码添加到dataGridView1_RowPostPaint事件中。

private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
    int count=0;
    if (dataGridView1.Rows.Count > 1)
    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        count++;
        foreach (DataGridViewCell cell in row.Cells)
        {
            if (Convert.ToInt32(cell) == 0)
            {
                label3.Text = count.ToString();
            }
        }
    }
}

我也尝试过这个:

private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
    int count=0;
    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        count++;
        foreach (DataGridViewCell cell in row.Cells)
        {
            if (cell.Value.ToString() == "0")
            {
                label3.Text = count.ToString();
            }
        }
    }
}

没有一个能正常工作。第一个根本不算。第二个代码给了我一个与An exception of type 'System.NullReferenceException' occurred in skraper.exe but was not handled in user code 相关的错误

你能帮我吗?

出现计数dataGridCells值

允许用户自己添加行,对吗?代码可以检测到最后一行,但它的值为null。NullReferenceException。所以你要做的是:

int zeros = 0;
foreach (DataGridViewRow row in dataGridView1.Rows) // For every row
    foreach (DataGridViewCell cell in row.Cells) // For every cell in the current row
        if (cell.Value != null) // If cell's value is not null
            if (cell.Value.ToString() == "0") // If cell's value is "0"
                zeros++; // Increase count
MessageBox.Show(zeros.ToString()); // Show result

我希望这能有所帮助。