Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to set row number in grid view

Tags:

c#

winforms

I need to set number of row in data grid view (like identity in sql) in winforms. i am dynamically adding columns and rows in grid view. any idea.

like image 405
Happy Avatar asked Dec 29 '13 08:12

Happy


2 Answers

To display text in the row header you can use the Row.HeaderCell.Value as shown below:

void dataGridView1_DataBindingComplete(object sender,
                         DataGridViewBindingCompleteEventArgs e)
{
    DataGridView gridView = sender as DataGridView;
    if (null != gridView)
    {
        foreach (DataGridViewRow r in gridView.Rows)
        {
            gridView.Rows[r.Index].HeaderCell.Value = 
                                (r.Index + 1).ToString();
        }
    }
}

This only displays the row number of the new row when the user begins typing in it. Not sure if there is a simple way of always showing the row number on the new row.

Another best way for asp.net application.Here is a link http://www.devcurry.com/2010/01/add-row-number-to-gridview.html

Just add the following tags to your section of your GridView

<Columns>                       
     <asp:TemplateField HeaderText="RowNumber">   
         <ItemTemplate>
                 <%# Container.DataItemIndex + 1 %>   
         </ItemTemplate>
     </asp:TemplateField>
     ...
</Columns>
like image 79
Chandan Kumar Avatar answered Nov 16 '22 23:11

Chandan Kumar


Method 1:

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

Method 2:

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

Method 3:

void GridView_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
   this.GridView.Rows[e.RowIndex].Cells[0].Value 
    = (e.RowIndex + 1).ToString();
}
like image 26
Vignesh Kumar A Avatar answered Nov 16 '22 23:11

Vignesh Kumar A