How to add an autonumber column in a DataGridView control that is populated with a DataTable in simple steps ?
Figure.1
The first column in Figure.1 displays sequential row numbers. I have achieved this output by using the following function.
private DataTable AutoNumberedTable(DataTable SourceTable)
{
AutoNumberColumn.ColumnName=
AutoNumberColumn.DataType =
AutoNumberColumn.AutoIncrement =
AutoNumberColumn.AutoIncrementSeed = 1;
AutoNumberColumn.AutoIncrementStep = 1;
ResultTable.Columns.Add(AutoNumberColumn);
ResultTable.Merge(SourceTable);
}
Refer http://msdn.microsoft.com/en-us/library/yctw654b.aspx on How to: Create an Autonumber DataColumn
Explanation
The function receives a DataTable as parameter. It create a Data Table, ResultTable. Then add a Data Column,AutoNumberColumn with auto incrementing behaviour. Then the SourceTable is merged with the ResultTable. The Merge method will add the rows of the source table to the destimation table one by one. Consequently, autonumber column values are generated as sequential row numbers
Implementation
In a few minutes, we will create a Windows Forms Application to test the case. Create a Windows Form and add a DataGridView. Write the following code in the Load event of the form.
private
using
Command.CommandText =
SqlDataAdapter
DataTable
dataAdapter.Fill(dataTable);
this
Then add the ConnectionString property given below and AutoNumberedTable function given above in the body of the form. Run the program. See what happens!
get
SqlConnectionStringBuilder
ConnectionBuilder.DataSource =
ConnectionBuilder.InitialCatalog =
ConnectionBuilder.UserID =
ConnectionBuilder.Password =
return
Refer http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnectionstringbuilder(VS.80).aspx on SqlConnectionStringBuilder Class
Details of Sample Application Seen in Figure.1
Database
Query :
Add the following namespaces on top.
How to : Add an autonumber column in a DataGridView
Basic password finder in C#
Thank you so much..It helped me...
Nima, Thank you for your support.
Wonderful Sir, Such works are very useful.... Please go on with such and more better works.
Hello, I am new in C#, coul dyou please help me for the below?I have my results (data content of a drive) in ListBox, how do I make the same in DataGridView?Thanks
I have try this ,but mine have sum of quantity at the bottom of the datagridview.I want the number only at the detail part.But the number goes on to the blank line and then to the sum of quantity.(I have 10 lines of details,followed by 1 blank line,followed by sum of quantity line)