.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal

Home >> Code Snippets >> Windows Form Controls >> Post New Resource Bookmark and Share   

 Subscribe to Code Snippets

auto generate row number to datagridview in windows application

Posted By:Amit Mehra       Posted Date: February 11, 2009    Points: 10    Category: Windows Form Controls    URL: http://www.dotnetspark.com  

Auto generate row number in DataGridView in windows application. Its simple below code shows how to do that.

Just you need to pass your datagridview in below function and it will generate auto number to Header cell.

NOTE: First you have to bind the datagridview with data then call the below function.

Using C# code

//Auto Generate mumber

public void AutoNumberRowsForGridView(DataGridView dataGridView)


if (dataGridView != null)


for (int count = 0; (count <= (dataGridView.Rows.Count - 2)); count++)


dataGridView.Rows[count].HeaderCell.Value = string.Format((count + 1).ToString(), "0");




In Vb.NET Example

Public Sub AutoNumberRowsForGridView(ByVal dataGridView As DataGridView)

If dataGridView IsNot Nothing Then

Dim count As Integer = 0

While (count <= (dataGridView.Rows.Count - 2))

dataGridView.Rows(count).HeaderCell.Value = String.Format((count + 1).ToString(), "0")

count += 1

End While

End If

End Sub

Hope this will help to all who want to add row number to datagridview dynamically.


Further Readings:

Author: Learning         Company URL: http://www.dotnetspark.com
Posted Date: October 30, 2012

this is what i have been waiting for and its superb . I have searched many sites but was never satisfied with the solution.

But request the authors to comment what the code does so that it would be helpfull for beginners like me.

Thanks Alot

Post Comment

You must Sign In To post reply
Find More code samples in C#, ASP.Net, Vb.Net and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend