To add a Serial Number as the first column in a GridView

I have a grid view. It has two related columns. I need to have a Serial Number column as the first column.

How can i do this? Thanks at Advance

+7
source share
7 answers

Create a datatable with two columns using the first column as auto-increment as true and AutoIncrementStep = 1, for example

DataTable _test = new DataTable(); DataColumn c = new DataColumn("sno", typeof(int)); c.AutoIncrement = true; c.AutoIncrementSeed = 1; c.AutoIncrementStep = 1; _test.Columns.Add(c); _test.Columns.Add("description"); gvlisting.DataSource = _test; 
+3
source
  <asp:TemplateField HeaderText="S No"> <ItemTemplate> <%# Container.DataItemIndex + 1 %> </ItemTemplate> <ItemStyle Width="2%" /> </asp:TemplateField> 
+17
source

This is more of a supporting answer to the original OP question. I had a terrible time figuring out how to get the index number (serial number in OP) of the line generated by R.Ilayaraja's answer (which BTW worked great).

In your code, page by page, if you want to get the index line number, you can use code similar to this:
Int32 idNumber = Convert.ToInt32(gvlisting.Rows[i].DataItemIndex.ToString()) + 1;

It is assumed that you used the "i" iterator to get other values ​​from your rows, and you need to add them to the number, since the index is ordinal (index 0 is the first row). If you are not using an iterator, just use .Rows[0]

I tried my best as an ASP.NET nugget to figure it out, so I decided that I would publish it in the hope that it would help someone else like me.

+3
source

Add a column named Ser and set it to ReadOnly=false .

Then add this code to your application:

 if (GridSearch.Rows.Count > 1) { for (int i = 0; i < GridSearch.Rows.Count-1; i++) { GridSearch.Rows[i].Cells[0].Value = (i + 1).ToString(); } 

}

+2
source

Just add this code to gridview

  <asp:TemplateField HeaderText="Serial No of Users"> <ItemTemplate> <%# ((GridViewRow)Container).RowIndex + 1%> </ItemTemplate> <FooterTemplate> <asp:Label ID="lbltotalall" runat="server" /> </FooterTemplate> </asp:TemplateField> 
+2
source
 <asp:TemplateField HeaderText="SR No"> <ItemTemplate> <%# Container.DataItemIndex + 1 %> </ItemTemplate> <ItemStyle Width="5%" /> </asp:TemplateField> 
+1
source

use the row index to bind the field or bind the row data, you can add a template column in which you can use the row index.

0
source

All Articles