C# 如何对DataGridView的行进行编号?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8769048/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 04:21:55  来源:igfitidea点击:

How to number the rows of DataGridView?

c#winformsdatagridview

提问by user891757

How to number the rows of datagridView ? That when I add additional row the number increments ?

如何对 datagridView 的行进行编号?当我添加额外的行时,数字会增加吗?

回答by Ali Foroughi

Add a column to your grid with title 'Number' (as first column) and put this code in its OnRowAdded event :

将一列标题为“Number”(作为第一列)的列添加到您的网格中,并将此代码放入其 OnRowAdded 事件中:

this.DataGridView1.Rows[e.RowIndex].Cells[0].Value = this.DataGridView1.Rows.Count;

you must fill your grid manually and do not bind it Edit:this does work on a bound list, so long as you bind it first then construct the list.

您必须手动填充网格并且不要绑定它 编辑:这确实适用于绑定列表,只要您先绑定它然后构建列表。

回答by Jayesh Goyani

//You can also use below code

this.DataGridView1.Rows[e.RowIndex].Cell[0].value =e.RowIndex + 1;

//get total number of rows

//获取总行数

this.DataGridView1.Rows.Count;

回答by adatapost

You should add AutoIncrementcolumn into DataTable. I presume that you have an instance dataTableof DataTable.

您应该将AutoIncrement列添加到DataTable. 我相信你有一个实例dataTableDataTable

//your code that populates the dataTable 

 DataColumn col1 = new DataColumn();
 col1.ColumnName  = "SrNo";
 col1.AutoIncrement = true;
 col1.AutoIncrementSeed = 1;
 col1.AutoIncrementStep = 1;

 dataTable.Columns.Add(col1);

 for(int i=0;i<dataTable.Rows.Count;i++)
  {
    dataTable.Rows[i]["SrNo"] = i + 1;
  }
 dataGridView1.DataSource = dataTable;

回答by General Grey

Ali Foroughi has the right idea, I slightly modified his answer to work with databound gridview as well as one manually built.

Ali Foroughi 有正确的想法,我稍微修改了他的答案以使用数据绑定 gridview 以及手动构建的一个。

add this to the RowsAdded Event Rows added fires everytime 1 or more rows are added. e.rowindex is the first row, e.rowcount is the total number of rows added.

将此添加到 RowsAdded 事件 每次添加 1 行或更多行时,添加的行都会触发。e.rowindex 是第一行,e.rowcount 是添加的总行数。

    private void dgv1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
    {
        for (int i=0;i<e.RowCount;i++)
        this.dgv1.Rows[e.RowIndex + i].Cells[0].Value = (e.RowIndex +i).ToString();
    }

Note:This assumes that the first column is your Row number column, change Cells[0] to Cells[n] where n= whichever column you have as your Row number column

注意:这假设第一列是您的行号列,将 Cells[0] 更改为 Cells[n],其中 n= 您作为行号列的任何列

回答by Malik Niaz

Rather use RowPostPaint event of datagridview

而是使用 datagridview 的 RowPostPaint 事件

void GridView_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
   this.GridView.Rows[e.RowIndex].Cells[0].Value 
    = (e.RowIndex + 1).ToString();
}

回答by Alex

What I did in the OnPageLoad after a loaded my datasource into gridview was to set a value in the RowHeaderCell with a simple loop:

在将我的数据源加载到 gridview 后,我在 OnPageLoad 中所做的是使用一个简单的循环在 RowHeaderCell 中设置一个值:

for (int i = 0; i < SensorGridView.Rows.Count; i++)
{
   DataGridViewRowHeaderCell cell = SensorGridView.Rows[i].HeaderCell;
   cell.Value = (i + 1).ToString();
      SensorGridView.Rows[i].HeaderCell = cell;
}

I tryed the the above sugestion with out the loop in both OnRowPostPaint and OnCellPostPaint they resulted with flikering row numbers

我在 OnRowPostPaint 和 OnCellPostPaint 都没有循环的情况下尝试了上述建议,结果是行号闪烁

Cheers

干杯

回答by Mike Banach

Based on what I learned here, then some experimentation, here is what worked for me in VB. It renumbers rows when a record is added or deleted.

根据我在这里学到的知识,然后进行一些实验,这是在 VB 中对我有用的方法。添加或删除记录时,它会重新编号行。

Private Sub NumberGridViewRows() Handles DataGridView1.RowsAdded, DataGridView1.RowsRemoved
    Dim row As DataGridViewRow
    For Each row In DataGridView1.Rows
        row.HeaderCell.Value = (row.Index + 1).ToString
    Next
End Sub

回答by Leonid

  1. add <asp:Label ID="rowNumber" runat="server" /> in <ItemTemplate>
  2. then add OnRowDataBound="gridEditorDocs_RowDataBound" to your GridView definition
  3. then add handler:

    protected void gridEditorDocs_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowIndex >= 0)
        {
            Label rowNumber = e.Row.FindControl("rowNumber") as Label;
            if (rowNumber != null)
                rowNumber.Text = string.Format("{0}.", e.Row.RowIndex + 1);
        }
    }
    
  1. 添加 <asp:Label ID="rowNumber" runat="server" /> in <ItemTemplate>
  2. 然后将 OnRowDataBound="gridEditorDocs_RowDataBound" 添加到您的 GridView 定义
  3. 然后添加处理程序:

    protected void gridEditorDocs_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowIndex >= 0)
        {
            Label rowNumber = e.Row.FindControl("rowNumber") as Label;
            if (rowNumber != null)
                rowNumber.Text = string.Format("{0}.", e.Row.RowIndex + 1);
        }
    }
    

回答by whitecore

Add a column to your grid with title 'Row Num' and convert it to template field

向网格中添加标题为“行号”的列并将其转换为模板字段

Eval RowIndex number and Convert it to integer and add one..

评估 RowIndex 编号并将其转换为整数并加一..

Or Copy below code inside your datagrid

或在您的数据网格中复制以下代码

               <asp:TemplateField HeaderText="Row Num">     
                    <ItemTemplate>
                        <asp:Label ID="lblRowNum" runat="server" Text='<%# Convert.ToInt32(DataBinder.Eval(Container, "RowIndex"))+1 %>'></asp:Label>
                    </ItemTemplate>
               </asp:TemplateField> 

回答by Death259

If you want to use the RowPostPaint event as Malik Niazhas suggested you might be better off to cast the sender as a DataGridView. This way you can copy and paste the code into any RowPostPaint event and be able to use it without any modification.

如果您想像Malik Niaz建议的那样使用 RowPostPaint 事件,则最好将发件人转换为 DataGridView。通过这种方式,您可以将代码复制并粘贴到任何 RowPostPaint 事件中,并且无需任何修改即可使用它。

((DataGridView)sender).Rows[e.RowIndex].HeaderCell.Value = (e.RowIndex + 1).ToString();

By using the RowPostPaint event though, I've found that it produces a few graphical issues. For starters the row numbers will flicker and the scroll bars will disappear. If you are manually loading your DataGridView and not binding it to a data source then you should be able to use the RowsAdded event. You can then use the exact same code as above.

不过,通过使用 RowPostPaint 事件,我发现它会产生一些图形问题。首先,行号会闪烁,滚动条会消失。如果您手动加载 DataGridView 并且未将其绑定到数据源,那么您应该能够使用 RowsAdded 事件。然后,您可以使用与上面完全相同的代码。

The alternative for those that are binding their DataGridView is to create a method to loop through and number each row.

绑定 DataGridView 的替代方法是创建一个方法来循环遍历每一行并对其进行编号。

private void numberMyGrid(DataGridView dgv)
{
    foreach (DataGridViewRow row in dgv.Rows)
    {
        row.HeaderCell.Value = (row.Index + 1).ToString();
    }
}

This can then be called after you load your data in the DataGridView.

这可以在您将数据加载到 DataGridView 中后调用。