<P><FONT size=1>All the list controls have an event by name "OnItemDataBound". We have to make use of this to create a serial number column or autogenerate numbers. <BR><BR>The basic steps which we need to keep in mind are as follows: <BR><BR><STRONG>Step1:</STRONG> Create a template column in the datagrid control. <BR></FONT></P> <PRE><FONT size=1> <Asp:TemplateColumn HeaderText="S.No" ItemStyle-HorizontalAlign="right">
<ItemTemplate>
</ItemTemplate>
</Asp:TemplateColumn></FONT></PRE><FONT size=1><STRONG>Step2:</STRONG> For OnItemDataBound assign an event name. That event would fire when an Item is databound to our datagrid. </FONT> <BLOCKQUOTE><FONT size=1><EM>For ex:</EM> OnItemDataBound = "populateSerialNumber"</FONT></BLOCKQUOTE><FONT size=1><STRONG>Step3:</STRONG> Write the code which would create the serial number with in the procedure "populateSerialNumber". </FONT> <PRE><FONT size=1> Sub populateSerialNumber(sender as object, objargs as DataGridItemEventArgs)
If objArgs.Item.ItemType <> ListItemType.Header Then
</FONT></PRE><FONT size=1><STRONG>The complete code listing follows:</STRONG></FONT> <P><FONT size=1>Pay particular attention to the <STRONG>populateSerialNumber</STRONG> procedure as discussed in step3. Note that I have specified datasetindex + 1 in the procedure below. This is because datasetindex value starts from 0. The "If" statement exists to ensure that our labels (row serial numbers) make more sense and to avoid any text from being displayed on the header. </FONT></P> <PRE><FONT size=1><%@ Page Language="VB" Debug="True" %>
<%@ Import namespace="System.Data" %>
<%@ Import namespace="System.Data.Oledb" %>
<script language="VB" runat="server">
Sub Page_Load (sender as object, e as eventargs)
BindAccess()
End sub
Sub BindAccess()
Dim strconn as string
Dim dtr as new oledbdataAdapter
dim ds as new dataset
strconn="PROVIDER=MICROSOFT.JET.OLEdb.4.0;DATA SOURCE="path of your database"
Dim cns as new oledbconnection(strconn)
cns.open()
strconn = "select title, qdate, email from tablename"
dtr = new oledbdataAdapter(strconn,cns)
dtr.fill(ds)
dtgrid.datasource = ds
dtgrid.databind()
End Sub
Sub populateSerialNumber(sender as object, objargs as DataGridItemEventArgs)
If objArgs.Item.ItemType <> ListItemType.Header Then
</FONT></PRE> <P><FONT size=1>* To test the above code with SQL Server (this code incidentally uses Ms Access as the datasource), replace all occurances of "oledb" with "sql" (Replace "System.Data.Oledb" with "System.Data.SQLClient"). You will need to make suitable changes to the connection string (strconn) as well.</FONT></P>