To add a Serial Number as the First Column in a GridView
I have a Grid View . It has two bound columns. I need to have a Serial Number column as th开发者_开发百科e first column.
How can i do that ? Thanks in Advance
<asp:TemplateField HeaderText="S No">
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
<ItemStyle Width="2%" />
</asp:TemplateField>
Create a datatable with two columns use a first column as autoincrement as true and AutoIncrementStep=1 like
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;
This is more of an adjunct answer to the OP's original question. I had a terrible time figuring out how to get the index number (serial number in the OP) of the row created by the R.Ilayaraja's answer (which worked great BTW).
In your code behind page if you want to get the index number of the row, you can use code similar to this:
Int32 idNumber = Convert.ToInt32(gvlisting.Rows[i].DataItemIndex.ToString()) + 1;
This assumes you were using an iterator 'i' to get other values from your rows, and you need to add one to the number since the index is ordinal (index 0 is the first row). If you're not using an iterator, just use .Rows[0]
I struggled mightily as an ASP.NET nugget to figure this out, so I figured I'd post this in hopes it helps some other noob like me.
Add a column called 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();
}
}
Just add this code in gridview
<asp:TemplateField HeaderText="Serial No of Users">
<ItemTemplate>
<%# ((GridViewRow)Container).RowIndex + 1%>
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="lbltotalall" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="SR No">
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
<ItemStyle Width="5%" />
</asp:TemplateField>
use Row index a bound field or on row data bound you can add a template column on which you could use the index of the row.
精彩评论