如何对GridView行自动编号?
2007-07-23 15:11
429 查看
有时候会遇到这样的情况,就是需要对GridView表格显示的结果增加一列自动递增编号列,以标示每一行的序号。要实现这一功能,首先在 GridView 第一列加入一个 TemplateField,并在 TemplateField 的 ItemTemplate 加入一个 Label (ID=lblNo),*.aspx 对应代码如下:
<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>
然后在 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);
}
}
如果遇到有分页时,以上代码对每一页都是从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);
}
}
<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>
然后在 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);
}
}
如果遇到有分页时,以上代码对每一页都是从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);
}
}
相关文章推荐
- 如何对GridView行自动编号?
- 如何对GridView行自动编号?
- 如何在WORD2010中取消自动编号?
- GridView 下增加自动编号列
- 如何重新恢复自动编号列的序号?
- GridView实现自动编号
- access如何用代码在“默认值”里实现自动编号?单据流水号生成问题。
- 如何让access自动编号从1开始排序实现方法
- 如何在ASPXGridView绑定数据不满一页时自动添加空行
- 在ORCAD里面如何给元器件自动编号
- GridView实现自动编号
- 如何让所请读取的数据自动产生编号.
- GridView加自动编号列
- 如何在DataGrid中添加自动编号的功能
- 如何让SELECT 查询结果额外增加自动递增序号 如果数据表本身并不内含自动递增编号的字段时,要怎么做才能够让SELECT查询结果额外增加自动递增序号呢?下列五种方法供您参考: USE test;
- SQL Server 如何重新恢复自动编号列的序号
- 在ORCAD里面如何给元器件自动编号
- GridView实现自动编号
- Excel如何实现表单编号自动递增?
- 关于如何在查询结果中添加自动编号