ASP.NET Code
  Home arrow ASP.NET Code arrow Displaying Serial numbers for rows in Data...
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  
Silverlight  
Visual Basic.NET  
Windows Scripting  
Windows Security  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
ASP Web Hosting  
ASP.NET Web Hosting 
Windows Web Hosting
 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 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
     
     
    ADVERTISEMENT



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


    Check out the new Jazz space on developerWorks

    <a href="http://zeus.developershed.com/shonuff.php?blackbird=3853&zoneid=442&source=&dest=http%3A%2F%2Fwww.ibm.com%2Fdeveloperworks%2Fspaces%2Fjazz%3FS_TACT%3D105AGY31%26S_CMP%3DDEVSHED&ismap="><img src="http://images.devshed.com/corp/img/news/jazz01.gif" alt="developerWorks Jazz space" align="left"></a>You've heard the buzz about Jazz... want to know more about it from a developer's perspective? Check out the Jazz space on developerWorks. This space is an up-to-date resource for developers, including technical information about Jazz and products built on Jazz, like Rational Team Concert Express. The Jazz space includes content from a wide variety of sources, including links, feeds, and comments from experts.
    FREE! Go There Now!


    NEW! A Layered approach to delivering security-rich Web applications

    As businesses grow increasingly dependent upon Web applications to provide services to customers, employees and partners, these complex applications become more difficult to secure. Although traditional security solutions protect Internet infrastructure layers, they do not guard against HTTP and HTML attacks. Many organizations that conduct security testing still deploy applications that allow attackers to manipulate their logic and wreak havoc on their business. To mitigate this risk, development and delivery teams must address Web application security throughout the lifecycle, addressing the many layers detailed in this paper.
    FREE! Go There Now!


    NEW! Develop Systems Software Assets with IBM Rational Asset Manager

    Join us for this on demand webcast to learn about developing complex systems more quickly and efficiently. We'll cover market drivers for developing, governing and reusing systems software assets and how you can develop system software assets with Rational Asset Manager.
    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! Download the free Web Application Security eKit

    Discover how IBM Rational AppScan Standard Edition can help you detext vulnerabilities in your web applications in the Web Application Security eKit. IBM Rational AppScan is a leading suite of automated web application security solutions that scan and test for common Web application vulnerabilities. The new Web Application Security eKit provides you with valuable resources, including white papers, demos, and additional information on the benefits of testing your Web applications.
    FREE! Go There Now!


    NEW! Project and Portfolio Management Executive Resource Kit

    Portfolio Management is about effectively managing portfolio value by aligning portfolio investments with business goals. This complimentary e-kit provides a collection of materials that can help you understand how IBM Rational enables and automates best practices for improved governance and clear visibility into portfolio and project performance across the entire IT project lifecycle.
    FREE! Go There Now!


    NEW! Successful Change and Release Management for .NET

    Join this webcast to discover the key requirements for successful change and release management. Learn how to extend your .NET environment to improve productivity and collaboration, and address core problems afflicting team development. In this webcast, we’ll review typical challenges faced by customers and how to resolve them with the IBM Rational Change and Release Management solution, including Rational ClearCase, Rational ClearQuest and Rational Build Forge. Replay is available for 9 months.
    FREE! Go There Now!


    NEW! Using Rational Business Developer to enhance your developer productivity

    Join this Rational Talks to You teleconference, to hear how Enterprise Generation Language (EGL) eliminates the need for tedious and error-prone low level coding, so developers can focus on business requirements. EGL extends the Rational software development platform with a simplified programming language that enables developers who have little or no experience with Java, Web technologies or Service Oriented Architecture, to create enterprise-class applications and services quickly and easily. It also allows developers who may have little or no mainframe programming experience to quickly create traditional mainframe components.
    FREE! Go There Now!


    NEW! Webcast: IBM Rational Build Forge - Beyond the Build

    The discipline of assembling and delivering software is maturing beyond standard developer-centric compile/test software builds. The end-to-end software development lifecycle is emerging as the new focus moves “Beyond the Build.” Join this on demand webcast to learn about methods for streamlining software delivery and key capabilities of the IBM Rational Build Forge framework for automating build and release management in environments of any size.
    FREE! Go There Now!


    NEW! Whitepaper: Delivering SOA solutions: service lifecycle management

    The unprecedented scope of a service-oriented architecture (SOA) initiative brings to the forefront a number of management and governance issues that were sidestepped in the past. The key to a successful SOA implementation is managing and governing activities throughout the entire SOA delivery lifecycle by ensuring that services conform to the needs of all of the business’s stakeholders. Learn how service lifecycle management allows the business to ensure that the process by which services are defined, created, tested, deployed, optimized and retired is manageable, repeatable and auditable.
    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





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 5 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek