在datagridview中显示序列号(DESC顺序)C#

时间:2016-09-21 12:49:01

标签: c# visual-studio-2010 datagridview row

我想在datagridview中将行号显示为DESC ORDER。

我在" RowPostPaint Event"中使用以下代码在datagridview中显示序列号。

        DataGridView grid = (DataGridView)sender;
        System.Drawing.Font rowFont = new System.Drawing.Font("Tahoma", 8f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, Convert.ToByte(0));

        dynamic centerFormat = new StringFormat();
        centerFormat.Alignment = StringAlignment.Far;
        centerFormat.LineAlignment = StringAlignment.Near;
        string rowIdx = (e.RowIndex + 1).ToString();
        Rectangle headerBounds = new Rectangle(e.RowBounds.Left, e.RowBounds.Top, grid.RowHeadersWidth, e.RowBounds.Height);
        e.Graphics.DrawString(rowIdx, rowFont, SystemBrushes.ControlText, headerBounds, centerFormat);
  

以上代码提供以下结果

1 2 3 。 。 10

Screen Short 1 - Result of above code

  

图片以下是我想要的样本

10 9 8 7 。 。 1

Screen Short 2 - A sample of what i want

第一种方法依赖于" RowIndex" 。是否有任何方法可以使用" RowCount"或类似的东西。

我希望以第二张图像的降序显示序列号。如何做到这一点......?

1 个答案:

答案 0 :(得分:0)

您可以通过减去grid.Rows.Counte.RowIndex来完成此操作。

请参阅以下代码。

DataGridView grid = (DataGridView)sender;
        System.Drawing.Font rowFont = new System.Drawing.Font("Tahoma", 8f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, Convert.ToByte(0));

        dynamic centerFormat = new StringFormat();
        centerFormat.Alignment = StringAlignment.Far;
        centerFormat.LineAlignment = StringAlignment.Near;
        string rowIdx = (grid.Rows.Count - e.RowIndex).ToString(); //you can get the row count and subtract it.
        Rectangle headerBounds = new Rectangle(e.RowBounds.Left, e.RowBounds.Top, grid.RowHeadersWidth, e.RowBounds.Height);
        e.Graphics.DrawString(rowIdx, rowFont, SystemBrushes.ControlText, headerBounds, centerFormat);