计算dataGridCells值的出现次数

时间:2016-07-30 16:10:16

标签: c#

我想知道0中有多少dataGridRows.Cells[1]。我将此代码添加到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();

            }
        }
    }
}

wchich都没有正常工作。第一个根本就算不上。第二个代码给出了与An exception of type 'System.NullReferenceException' occurred in skraper.exe but was not handled in user code

相关的错误

你能帮帮我吗?

1 个答案:

答案 0 :(得分:1)

允许用户自己添加行吗?最后一行可以通过代码检测到,但它的值为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

我希望这会有所帮助。