将DataGridView的最后一行冻结为列的总和?

问题描述:

可以将最后一行 DataGridView 作为列的总和,最后一行是否会显示/被冻结?

Is it possible to make the last row of a DataGridView as the sum of the columns, and that the last row always will show/be frozen?

解决方案其实很简单,只需要你一点点思考。

The solution is actually very simple, and just requires you to think outside the box a little.

通常,一旦数据被加载到网格视图中,底部就会有一个深灰色的行:

Usually, once data is loaded into your grid view, there's a dark grey row at the bottom of it:

您可以使用此空间来获得优势。所有你需要做的是将几个标签拖到窗体上,放置在网格视图内,应用背景颜色:

You can use this space to your advantage. All you need to do is drag a few labels onto your form, placed just inside your grid view, with a background colour applied:

在你的代码中添加一个这样的方法:

Within your code, add a method like this:

void UpdateTotal(Label Label, int Number)
{
    // Called from another thread; facilitate safe cross-thread operation
    if(this.InvokeRequired)
        this.Invoke(new Action<Label, int>(UpdateTotal), new object[] {Label, Number});

    // Called from this thread or invoked
    else
        // Format the number with a thousands separator
        Label.Text = Number.ToString("N0");
}

然后,从更新网格视图的任何位置,调用 UpdateTotal(labelPostsAffected,2000); ,使用您的标签名称,以及您计算的总和(或在方法中计算)。

Then, from wherever you update your grid view, call UpdateTotal(labelPostsAffected, 2000);, using the name of your label, and the sum you've calculated (or calculate it in the method).

结果是这样的: