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.
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>
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With