How to set line number in grid view

I need to set the number of rows as a data grid (e.g. id in sql) in winforms. I am dynamically adding columns and rows as a grid. any idea.

+4
source share
3 answers

To display the text in the line header, you can use Row.HeaderCell.Valueas 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 displays the line number of the new line when the user begins to enter text into it. Not sure if there is an easy way to always show the line number on a new line.

  
    

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

    

GridView

<Columns>                       
     <asp:TemplateField HeaderText="RowNumber">   
         <ItemTemplate>
                 <%# Container.DataItemIndex + 1 %>   
         </ItemTemplate>
     </asp:TemplateField>
     ...
</Columns>
+8

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;

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

3:

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

Why not. First create the data and then snap to the grid as shown below.

DataTable tbl = new DataTable();
Datacolumn dc = new Datacolumn("ID");
Datacolumn dc1 = new Datacolumn("col1");

Datarow dr = tbl.NewRow();

dr[dc] = "123";
dr[dc1] = "SomeData";

tbl.Rows.Add(dr);

DataGridView.DataSource = tbl;
0
source

All Articles