ASP.NET Code
  Home arrow ASP.NET Code arrow Displaying Serial numbers for rows in Data...
Iron Speed
ASP Free Forums 
.NET  
ASP  
ASP Code  
ASP.NET  
ASP.NET Code  
BrainDump  
C#  
Code Examples  
Database  
Database Code  
IIS  
Microsoft Access  
MS SQL Server  
Visual Basic.NET  
Windows Scripting  
Windows Security  
XML  
ASP Web Hosting  
ASP.NET Web Hosting 
Dedicated Servers 
Download TestComplete 
Windows Web Hosting
 
IBM® developerWorks 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
IBM Rational Software Development Conference
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
ASP.NET CODE

Displaying Serial numbers for rows in DataGrid.
By: aspfree
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 16
    2002-10-13

    Table of Contents:

    Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    Iron Speed
     
    ADVERTISEMENT

    Ajax Application Generator Generate database and reporting .NET Web apps in minutes. Quickly create visually stunning, feature-rich apps that are easy to customize and ready to deploy. Download Now!


    <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>     &lt;Asp:TemplateColumn HeaderText="S.No" ItemStyle-HorizontalAlign="right"&gt;

            &lt;ItemTemplate&gt;       

            &lt;/ItemTemplate&gt;

         &lt;/Asp:TemplateColumn&gt;</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 &lt;&gt; ListItemType.Header Then

             objArgs.Item.Cells(0).text = objArgs.Item.datasetindex + 1

           End If 

        End sub

    </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>&lt;%@ Page Language="VB" Debug="True" %&gt;

    &lt;%@ Import namespace="System.Data" %&gt;

    &lt;%@ Import namespace="System.Data.Oledb" %&gt;

     

    &lt;script language="VB" runat="server"&gt;

        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 &lt;&gt; ListItemType.Header Then

             <STRONG>objArgs.Item.Cells(0).text = objArgs.Item.datasetindex + 1</STRONG>

           End If 

        End sub

    &lt;/script&gt;

     

    &lt;form name="ListOpenQuestion" id="ListOpenQuestion" Runat="server"&gt;

        &lt;Asp:DataGrid Runat="server" id="dtgrid"

                <STRONG>OnItemDataBound = "populateSerialNumber"</STRONG>

                AutoGenerateColumns=false

                Width="75%"

                Align="center"&gt;

        &lt;Columns&gt;

     

          <STRONG>&lt;Asp:TemplateColumn HeaderText="S.No" ItemStyle-HorizontalAlign="right"&gt;

             &lt;ItemTemplate&gt;       

             &lt;/ItemTemplate&gt;

           &lt;/Asp:TemplateColumn&gt;</STRONG>

     

           &lt;Asp:HyperLinkColumn DataTextField="qtitle"

                   DataNavigateUrlFormatstring="reply.aspx?id={0}"

                   DataNavigateUrlField="qid" HeaderText="Question Title"/&gt;

     

           &lt;Asp:BoundColumn DataField="qDate"

                   HeaderText="Date Posted"

                   ItemStyle-HorizontalAlign="right" /&gt;

     

           &lt;Asp:HyperLinkColumn DataTextField="email"

                   DataNavigateUrlFormatString="mailto:{0}"

                   DataNavigateUrlField="email"

                   HeaderText="Posted By"/&gt;

        &lt;/Columns&gt;

        &lt;/Asp:DataGrid&gt;

    &lt;/form&gt;

    </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>


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

    More ASP.NET Code Articles
    More By aspfree

     

    IBM® developerWorks developerWorks - FREE Tools!


    NEW! Application development for the OLPC laptop

    The XO laptop (of the One-Laptop-Per-Child initiative) is an inexpensive laptop project intended to help educate children around the world. The XO laptop includes many innovations, such as a novel, inexpensive, and durable hardware design and the use of GNU/Linux as the underlying operating system. The XO also includes an application environment written in Python with a human interface called Sugar, accessible to everyone (including kids). Explore the Sugar APIs and learn how to develop and debug a graphical activity in Sugar using Python.
    FREE! Go There Now!


    NEW! BlammoSplat: Build a community Web site of OpenLaszlo animations, Part 3: The community animation

    Learn to enable users to both rate existing animations and to combine existing animations into new snippets. This is the third in a series of three tutorials that chronicle the building of a site that enables collaborative discussion and animation building using Domino and OpenLaszlo.
    FREE! Go There Now!


    NEW! Develop with Java and PHP technology on AIX Version 5.3, Part 6: Building the Java business application

    Set up a PHP Web interface for the Java(TM) business application using a database created in earlier in this series. The PHP Web interface collects information from users and sends the session data to the Java business application for processing and for a response.
    FREE! Go There Now!


    NEW! Don't wait! Try the Rational Application Developer (RAD) v7.5 open beta code today

    Download the Rational Application Developer (RAD) v7.5 open beta code and start developing applications for the JEE5 standard which features EJB3.0, JPA, JSF 1.2, JSP 2.1 and Servlet 2.5 standards. When you use this beta you will see how you can increase developer productivity for already existing applications with improved support for refactoring, as well as adding new features to existing applications. In addition, the beta provides tooling for JD Edwards, Oracle, SAP, Siebel and PeopleSoft to improve the developer productivity with these enterprise systems.
    FREE! Go There Now!


    NEW! Hello World: Monitor a simple business process using WebSphere Business Monitor V6.0.2

    This tutorial shows new users of IBM WebSphere Business Monitor Version 6.0.2 how to perform the "Hello World" equivalent for monitoring business process applications. It is intended to help you get familiar with the capabilities of the product.
    FREE! Go There Now!


    NEW! Rational Talks to You: Scott Ambler on being agile in a global development environment

    Join this Rational Talks to You teleconference on December 6 at 1:00 pm ET to participate in an agile application development discussion and get your questions answered on using IBM Rational Method Composer in a distributed environment.Get your questions answered!
    FREE! Go There Now!


    NEW! Trial download: IBM Informix Dynamic Server Express Edition V11.0

    Informix Dynamic Server (IDS) Express Edition offers outstanding online transaction processing (OLTP) database performance, while helping to simplify and automate many of the tasks associated with deploying databases for small business applications. IDS 11 further extends the ease of management and applications integration with the Admin API and Scheduler, high availability with Continuous Log Restore for backup server recovery in case of a primary server failure, and column level encryption to protect personal and company private data.
    FREE! Go There Now!


    NEW! Trial download: IBM Lotus Forms V3.0

    Get a free trial download of IBM Lotus Forms V3.0 (formerly Workplace Forms), which provides a zero-footprint eForms solution to help you automate and move forms-based business processes off the desktop and onto the Web. With Lotus Forms, you can extend applications beyond the firewall by creating a single electronic form document ready for use in both thick and Web 2.0 thin client format.
    FREE! Go There Now!


    NEW! Try the IBM SOA Sandbox for Connectivity

    Visit IBM developerWorks to try the IBM SOA Sandbox for connectivity. The SOA Sandbox for connectivity provides a trial environment with the tooling and components to help you explore how to effectively connect your infrastructure and integrate all of the people, processes and information in your company. Use the hosted sandbox to explore SOA techniques that streamline connecting existing IT assets together, as well as learn how to connect them to new business logic.
    FREE! Go There Now!


    NEW! Webcast: What is new in Viper 2 for developers?

    Viper 2 brings a great value to developer communities including SQL, XML, PHP, Ruby, .NET and Java. You probably already know that DB2 Express-C is free for developers to develop, deploy and distribute. Viper 2 provides a variety of means that help move your application from the development stage to deployment more rapidly. This webcast shows how to best utilize the latest tools available for developing DB2 applications.
    FREE! Go There Now!



    All FREE IBM® developerWorks Tools!

    ASP.NET CODE ARTICLES

    - How to Use the ListBox Control in ASP.NET 2.0
    - How to Load XML Documents in ASP.NET 2.0
    - DataGrid Code
    - ASP.NET Guestbook
    - User Controls and Client Side Scripting
    - ASP.NET Programming with Microsoft's AS...
    - ASP.NET Basics (part 3): Hard Choices
    - ASP.NET Basics (part 2): Not My Type
    - ASP.NET Basics (part 1): Nothing But .Net
    - Directory Tree Browser
    - How to get the confirmation of Yes/No from a...
    - Complete example using custom errors and wri...
    - Paging Certain # records per page .NET style
    - General Methods of formatting and Subtractin...
    - .NET LinkButton web control

     
    Accelerating Trading Partner Performance
     
    Competing on Analytics
     
    Cost Effective Scaling with Virtualization and Coyote Point Systems
     
    Five Checkpoints to Implementing IP Telephony
     
    Hosted Email Security: Staying Ahead of New Threats
     




    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 6 hosted by Hostway