有时候会遇到这样的情况,就是需要对GridView表格显示的结果增加一列自动递增编号列,以标示每一行的序号。要实现这一功能,首先在 GridView 第一列加入一个 TemplateField,并在 TemplateField 的 ItemTemplate 加入一个 Label (ID=lblNo),*.aspx 对应代码如下:
如果遇到有分页时,以上代码对每一页都是从1开始编号,所以对于有分页的情况需要修改成:
<
asp:GridView
ID
="GridView1"
runat
="server"
AllowPaging
="True"
AutoGenerateColumns
="False"
DataKeyNames ="Flag,ID" DataSourceID ="SqlDataSource1" EmptyDataText ="无记录。" >
< Columns >
< asp:TemplateField HeaderText ="编号" >
< ItemTemplate >
< asp:Label ID ="lblNo" runat ="server" Text ="Label" ></ asp:Label >
</ ItemTemplate >
< ItemStyle Wrap ="True" />
< HeaderStyle Wrap ="False" />
</ asp:TemplateField >
</ Columns >
</ asp:GridView >
DataKeyNames ="Flag,ID" DataSourceID ="SqlDataSource1" EmptyDataText ="无记录。" >
< Columns >
< asp:TemplateField HeaderText ="编号" >
< ItemTemplate >
< asp:Label ID ="lblNo" runat ="server" Text ="Label" ></ asp:Label >
</ ItemTemplate >
< ItemStyle Wrap ="True" />
< HeaderStyle Wrap ="False" />
</ asp:TemplateField >
</ Columns >
</ asp:GridView >
然后在 GridView 的 RowDataBound 事件中,设定每一列的 lblNo 的 Text 属性值为 RowIndex + 1(因为 RowIndex 起始编号为 0 ,所以每一行的自动编号为 RowIndex + 1) 。
protected
void
GridView1_RowDataBound(
object
sender, GridViewRowEventArgs e)
{
Label olabel;
if (e.Row.RowType == DataControlRowType.DataRow)
{
olabel = (Label)e.Row.Cells[ 0 ].FindControl( " lblNo " );
olabel.Text = Convert.ToString(e.Row.RowIndex + 1 );
}
}
{
Label olabel;
if (e.Row.RowType == DataControlRowType.DataRow)
{
olabel = (Label)e.Row.Cells[ 0 ].FindControl( " lblNo " );
olabel.Text = Convert.ToString(e.Row.RowIndex + 1 );
}
}
如果遇到有分页时,以上代码对每一页都是从1开始编号,所以对于有分页的情况需要修改成:
protected
void
GridView1_RowDataBound(
object
sender, GridViewRowEventArgs e)
{
Label olabel;
if (e.Row.RowType == DataControlRowType.DataRow)
{
olabel = (Label)e.Row.Cells[ 0 ].FindControl( " lblNo " );
olabel.Text = Convert.ToString(GridView1.PageIndex * GridView1.PageSize + e.Row.RowIndex + 1 );
}
}
{
Label olabel;
if (e.Row.RowType == DataControlRowType.DataRow)
{
olabel = (Label)e.Row.Cells[ 0 ].FindControl( " lblNo " );
olabel.Text = Convert.ToString(GridView1.PageIndex * GridView1.PageSize + e.Row.RowIndex + 1 );
}
}