简体   繁体   中英

How to number the rows of DataGridView?

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

Rather use RowPostPaint event of datagridview

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

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:

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

Cheers

//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;

You should add AutoIncrement column into DataTable . I presume that you have an instance dataTable of DataTable .

//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;

Most of these solutions work for initially adding row numbers. However, if you add the row numbers to the row header and then reorder a column, they all disappear . So what you should do is use DataGridViewBindingCompleteEventHandler to add the row numbers whenever the data bindings change

public partial class MyForm : Form
{
    public MyForm()
    {
        InitializeComponent();

        this.dGV.DataBindingComplete += 
            new DataGridViewBindingCompleteEventHandler(this.DataBindingComplete);
    }

    // ...

    private void DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
    {
        // Loops through each row in the DataGridView, and adds the
        // row number to the header
        foreach (DataGridViewRow dGVRow in this.dGV.Rows)
        {
            dGVRow.HeaderCell.Value = String.Format("{0}", dGVRow.Index + 1);
        }

        // This resizes the width of the row headers to fit the numbers
        this.dGV.AutoResizeRowHeadersWidth(DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders);
    }
}

With this code, when you add a row, delete a row, reorder columns, etc., the row numbers will remain.

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

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.

    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

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..

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> 

If you want to use the RowPostPaint event as Malik Niaz has 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.

((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.

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

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.

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

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.

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.

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
  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); } } 

If you want to see the row # in the row header (ie, not in the grid) be sure to use the HeaderCell property of the Rows[] as follows. This handles the RowPostPaint event of the datagridview.

private void dgvUserAct_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
  this.dgvUserAct.Rows[e.RowIndex].HeaderCell.Value = (e.RowIndex + 1).ToString();
}

An even easier way is to set the row header values in the pre paint. You then need to make sure they are not already set on future paints because setting the value causes another paint. This snippet worked for me and does not cause continuous paints. This will also keep the rows numbered correctly (1..nn) even if you sort add or remove rows. Works fine with binding.

    private void dgv_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
    {
        String hdrNum =  String.Format("{0}", e.RowIndex + 1);

        if (dgvResults.Rows[e.RowIndex].HeaderCell.Value == null || hdrNum != dgvResults.Rows[e.RowIndex].HeaderCell.Value.ToString())
        {
            dgvResults.Rows[e.RowIndex].HeaderCell.Value = hdrNum;
        }
    }

I know it is very old topic, but just for the record, once we needed to figure out a quick solution just how to number rows in DataGridView. The program, composed of many DataGridViews, many dlls, using 3 different SQL engines, and the tables with no record numbers... So as a quick solution we used CellFormating Event. Today, I am not sure if this was a good idea, but for then it worked perferctly.

Here is the sample code:



 this.DataGridView1.CellFormatting += new System.Windows.Forms.DataGridViewCellFormattingEventHandler(this.DataGridView1_CellFormatting);
            
     private void DataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
     {
        //We put the numbers into first cell
        if (e.ColumnIndex == 0) { e.Value = e.RowIndex + 1; } 
     }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM