使用C#在datagrid中对行标题编号

时间:2010-08-05 17:37:48

标签: c# wpf

大家好我正在使用datagrid并且它没有自动编号。所以我使用以下方法在rowheader中编号,但问题是数字是重复的,当他们对列进行排序时,他们正在重新排列自己。当我滚动页面时,当行离开可见性时,当你再次向后滚动时它的数字正在改变...例如在页面加载时你会看到1到30顺序,当你向上和向下滚动两次,订单可以变成1,30,25,4,......等......没有特定的顺序..它在行标题中显示随机数.. 请为我建议出路

在XAML页面中,我按以下方式调用该方法 LoadingRow = “dg_expSummary_LoadingRow”

在后端,代码如下

private void dg_expSummary_LoadingRow(object sender, DataGridRowEventArgs e)
{
   e.Row.Header = e.Row.GetIndex() + 1;
}

3 个答案:

答案 0 :(得分:0)

尝试在适当的时间设置一次列名。例如。设置数据源后。

答案 1 :(得分:0)

我在VB.Net中这样做。将原始结果集行号存储在Row(x).Column(0).Tag中,然后:

Private Sub gridData_RowPostPaint(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewRowPostPaintEventArgs) Handles gridData.RowPostPaint

    Dim style As DataGridViewCellStyle
    Dim Pen As Pen
    Dim rec As RectangleF
    Dim format As StringFormat
    'Dim n As Integer

    'get style to use for row header cells            
    style = gridData.RowHeadersDefaultCellStyle

    'get pen (needed to get text brush)            
    Pen = New Pen(style.ForeColor)

    'get row rectangle and adjust to width of row header            
    rec = e.RowBounds
    rec.Width = gridData.RowHeadersWidth

    'create formating object to center row number            
    format = StringFormat.GenericTypographic
    Format.Alignment = StringAlignment.Center
        Format.LineAlignment = StringAlignment.Center

        'draw the row number in row header            
        e.Graphics.DrawString(gridData.Rows.Item(e.RowIndex).Cells(0).Tag.ToString(), style.Font, Pen.Brush, rec, format)

    End Sub

我的代码改编自此处的c#示例: http://www.daniweb.com/forums/thread302079.html

答案 2 :(得分:0)

在XAML中为您的DataGrid设置此属性

VirtualizingStackPanel.VirtualizationMode =“标准”