开发者

C# Datatable Compute on Index instead of Name?

I am using a Datatable in ASP.NET / C# and would like to use the Compute method to sum each column, is there a way of doing this based on column index rather than column name so I can just place it in a for loop along the lines of:

for (int i = 0; i < dt.Columns.Count; i++)
        {
            GridView1.FooterRow.Cells[i].Text = dt.Compute("SUM(开发者_如何学编程i)", "").ToString();
        }

It's not overly critical to my application as I will be using an array of the column names elsewhere so I can use that array to construct the SUM with the name.


It doesn't look like expressions used by DataTable.Compute support referring to columns by index. In fact, the MSDN documentation for the DataColumn.Expression property emphasizes the use of column names:

When you create an expression, use the ColumnName property to refer to columns.

You could use the ColumnName property in your loop to refer to the current column's name, as @paolo suggested in the comments to your question. This would look like:

for (int i = 0; i < dt.Columns.Count; i++)
{
    string expression = "SUM(" + dt.Columns[i].ColumnName + ")";
    GridView1.FooterRow.Cells[i].Text = dt.Compute(expression, "").ToString();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜