Wednesday, May 16, 2007

Auto Numbering in Grid view

this article shows how to do auto numbering in grid view

in some cases we need to provide numbering of rows

in the folowing example i have connected a datatable with grid view

here is the htmnl code of grid view



<asp:GridView ID="GridView1" runat="server" AllowPaging="True" OnRowDataBound="GridView1_RowDataBound" AutoGenerateColumns="False" ShowFooter="True" PageSize="5" OnPageIndexChanging="GridView1_PageIndexChanging">
<Columns>
<asp:TemplateField HeaderText="No" Visible="False"></asp:TemplateField>
<asp:BoundField DataField="name" HeaderText="Name" />
<asp:BoundField DataField="gender" HeaderText="Gender" />

<asp:BoundField DataField="origin" HeaderText="Origin" />
</Columns>
</asp:GridView>




protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
DataRowView drv = (DataRowView) e.Row.DataItem;

if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[0].Text = Convert.ToString(e.Row.DataItemIndex + 1);
if (drv["gender"].ToString() == "M")
{
e.Row.Cells[3].Text = "Male";
}
else
{
e.Row.Cells[3].Text = "Female";

}

}
}


e.Row.Cells[0].Text = Convert.ToString(e.Row.DataItemIndex + 1);
is the line giving auto numbering

also the datatable has a field called gender which contains the value M/F

if it is M cell will contain Male
if it is F cell will contain Female

No comments: