2014-09-06 111 views
0

我正在使用Windows应用程序与C#。 我想在datagridview中显示序列号。如何在datagridview中显示序列号?

+0

被网格行是固定的? – andy 2014-09-06 07:38:02

+0

行数大部分没有在datagridview中修复 – 2014-09-06 07:40:49

+0

Krushnakant Ladani是对的,网格的行不固定。 – 2014-09-06 07:43:05

回答

2

您需要绑定datagridview的DataBindingComplete事件。

private void gridStateZone_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e) 
    { 
     LoadSerial(gridStateZone); 
    } 


private void LoadSerial(DataGridView grid) 
    { 
     foreach (DataGridViewRow row in grid.Rows) 
     { 
      grid.Rows[row.Index].HeaderCell.Value = string.Format("{0} ", row.Index + 1).ToString(); 
      row.Height = 25; 
     } 
    } 

这对我很有用。

1

在WinForms Applications中,为了显示行标题中的行号,我们可以使用DataGridView控件的RowPostPaint事件。

用法:假设网格被命名为dgvUserDetails

代表

this.dgvUserDetails.RowPostPaint += new System.Windows.Forms.DataGridViewRowPostPaintEventHandler(this.dgvUserDetails_RowPostPaint); 

代码

private void dgvUserDetails_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e) 
{ 
     using (SolidBrush b = new SolidBrush(dgvUserDetails.RowHeadersDefaultCellStyle.ForeColor)) 
     { 
       e.Graphics.DrawString((e.RowIndex + 1).ToString(), e.InheritedRowStyle.Font, b, e.RowBounds.Location.X + 10, e.RowBounds.Location.Y + 4); 
     } 
} 

不要试图操纵代码部分,因为X和Y在行标题区域是计算出的坐标,或者您可以自己定制测试它以查看各种结果。

结果

enter image description here

link

0
private void grid_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e) 
    { 
     using (SolidBrush b = new SolidBrush(((DataGridView)sender).RowHeadersDefaultCellStyle.ForeColor)) 
     { 
      e.Graphics.DrawString((e.RowIndex + 1).ToString(), e.InheritedRowStyle.Font, b, e.RowBounds.Location.X + 10, e.RowBounds.Location.Y + 4); 
     } 
    }