ASP.NET Code
  Home arrow ASP.NET Code arrow .NET LinkButton web control
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 
 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

.NET LinkButton web control
By: Troy Karhoff
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 17
    2003-06-01

    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!

    This article covers a fundamental use of the .NET LinkButton web control for page postbacks.A web developer is routinely faced with the challenge of knowing which link was clicked. The typical solution involves passing information on the querystring in the clear, like this: "GetProduct.asp?ID=3762". A key benefit of the LinkButton web control is the power to know which link was clicked by using POST rather than GET. This is accomplished by setting 2 properties on the LinkButton: CommandName and CommandArgument. These properties are passed into the onCommand event when the user clicks a LinkButton. In the event handler for onCommand, the CommandName and CommandArgument properties can be evaluated in CommandEventArgs. Because this all takes place in the POST, the querystring is shorter and the postback data is hidden. Let's begin by looking at some code. First, a "mini" database of products is created in the code using two instances of System.Collection.Hashtable. One hashtable stores the ProductId and ProductTitle, and the other hashtable stores the ProductId and ProductDescription. The two Hashtables are related by the ProductId. This technique is OK for demonstration purposes; however, there are cleaner ways to accomplish this.


    Hashtable hashProductName = new Hashtable();
        
    Hashtable hashProductDesc = new Hashtable();

    void BuildMiniDatabase()
        {
            
    hashProductName[0] = "Jalapeno Dip" ;
            
    hashProductDesc[0] = "Simmered in mayonaise and wine, this Jalapeno Dip will make your eyes water" ;

            
    hashProductName[1] = "Smoked Sausage" ;
            
    hashProductDesc[1] = "Mouth watering and delicious sausage" ;

            
    hashProductName[2] = "Shrimp Fiesta" ;
            
    hashProductDesc[2] = "East Coast's finest shrimp" ;

            
    hashProductName[3] = "Jerk Chicken" ;
            
    hashProductDesc[3] = "A real island experience you will not forget" ;

            
    hashProductName[4] = "Beer-Battered Fish" ;
            
    hashProductDesc[4] = "Pabst Blue Ribbon and Fish. Wow!" ;

            
    hashProductName[5] = "Bacon Burger" ;
            
    hashProductDesc[5] = "Big, juicy, and bursting with flavor" ;

            
    hashProductName[6] = "Sirloin Tip" ;
            
    hashProductDesc[6] = "Delicate cuts with no fat" ;

            
    hashProductName[7] = "Baked Alaska" ;
            
    hashProductDesc[7] = "Fine dessert comprised of sponge cake topped with ice cream and covered with meringue. The meringue is browned before the ice cream can melt." ;

            
    hashProductName[8] = "Fried Chicken" ;
            
    hashProductDesc[8] = "Country cookin'" ;

            
    hashProductName[9] = "Fresh Garden Salad" ;
            
    hashProductDesc[9] = "Crispy iceberg lettuce and a garden of vegtables" ;

            
    hashProductName[10] = "One Pea" ;
            
    hashProductDesc[10] = "A single green pea that will leave you craving more" ;

        }

    Next, the web page layout is very basic. Inside a form, a table is built with 2 columns. The left side cell will hold the product links. The right cell will display the product description.


    <body>
    <
    form id="MainForm" method="post" runat="server" >
    <
    asp:Table CellPadding=6 CellSpacing=2 BorderColor="#DDDDDD" BorderStyle=Solid BorderWidth=2 Runat=server>
    <
    asp:TableRow Runat=server>
      <
    asp:TableCell id=LinkList Wrap=False BackColor="#FFFFFF" Runat=server/>
      <
    asp:TableCell id="tablecellMessage" CssClass="ProductDesc" Runat=server></asp:TableCell>
    </
    asp:TableRow>
    </
    asp:Table>
    </
    form>
    </
    body>

    Now that the web page is designed, the LinkButtons can be added. The LinkButtons are added dynamically using code. The System.Web.UI.WebControls.LinkButton control is instantiated and assigned to _LB1. The Text property is used for rendering the hyperlink label. That is, the text that sits between . The CommandName and CommandArgument are what's it all about. Use the CommandArgument property to specify an argument that complements the CommandName property. What might have been placed on the querystring, will now simply be assigned in the CommandName and/or CommandArgument properties. In my example, I'm really just using the CommandArgument property for storing the ProductId of each product link. The CommandName is used to identify my grouping of links which happen to be the same - they're all products.


    void BuildLinkList()
        {
            for (
    int i=1i<=10i++)
            {
                
    LinkButton _LB1 = new LinkButton();
                
    _LB1.Text hashProductName[i].ToString();
                
    _LB1.CssClass "ProductLinks";
                
    _LB1.CommandName "Products";
                
    _LB1.CommandArgument i.ToString() ;

    The onCommand event is fired when a user clicks a LinkButton. Because my LinkButtons are added programatically, I need to wire the onCommand event to the control and assign it to the OnLinkClick event handler.


               _LB1.Command += new System.Web.UI.WebControls.CommandEventHandler(OnLinkClick);

                
    LinkList.Controls.Add(_LB1);
                
    LinkList.Controls.Add(new LiteralControl("
    "
    )); 

    When the user clicks a product link, the OnLinkClick event handler will determine which link was clicked, get the ProductId from the CommandArgument property, retrieve the ProductDescription from the mini database, and display the result on the web page.


        void OnLinkClick(object OSystem.Web.UI.WebControls.CommandEventArgs E)
        {
            
    int RecordId Int32.Parse(E.CommandArgument.ToString());
            
    tablecellMessage.Text "<b>" hashProductName[RecordId].ToString() + "</b>
    <i>" 
    hashProductDesc[RecordId].ToString() + "</i>";
        }

    The LinkButton web control will most likely become a fundamental part of your ASP.Net programming.
    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 Troy Karhoff

     

    IBM® developerWorks developerWorks - FREE Tools!


    NEW! Implement new security capabilities in DB2 9.5, Part 1: Understanding roles in DB2 9.5

    IBM DB2 9.5 provides new options for tighter security, and allows for more granularity and flexibility in administration of the database. This tutorial is the first of two tutorials that cover roles and trusted contexts. Follow the exercises in this tutorial, and learn how to take advantage of the new DB2 feature roles in combination with other essential e-business technologies such as Web services, Web application server, and DB2 database server.
    FREE! Go There Now!


    NEW! Rational 'Talks to You' Teleconference Series

    This Fall, IBM Rational talks to you directly through a special teleconference series giving you access to the best minds in IBM Rational - product experts and market thought leaders who will answer your questions during these pre-scheduled telephone conference calls. Register today!
    FREE! Go There Now!


    NEW! Rational Modeling Extension for Microsoft.Net

    Rational Modeling Extension for Microsoft .NET enhances usability for code generation supporting a more intelligent refactoring. The latest enhancements enable organizations with Java and .NET systems and software development maintain architectural integrity across heterogeneous platforms.
    FREE! Go There Now!


    NEW! Spot defects early with Continuous Integration

    Continuous Integration (or CI) is a process that consists of continuously compiling, testing, inspecting, and deploying source code. In many Continuous Integration environments, this means running a new build anytime code within a source code management repository changes. The benefit of CI is simple: assembling software often greatly increases the likelihood that you will spot defects early, when they still are relatively manageable. In this tutorial, a companion to his series In pursuit of code quality, Andrew Glover introduces the fundamental aspects of Continuous Integration and steps you through how to set up a CI process using best-of-breed open source technologies.
    FREE! Go There Now!


    NEW! The role of integrated requirements management in software delivery

    This paper is about the critical role that a discipline called integrated require­ments management can play in helping to ensure that your business goals and IT investments are continuously aligned—whether you are sourcing, integrat­ing, building or maintaining software. It also looks at ways that automated IBM Rational® products can work together to help you use requirements in the very best way.
    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! Web development with Eclipse Europa, Part 1: The Java EE for Eclipse

    It's a good time to be a Web developer. You've never had more choices in terms of technologies. There are so many great open source Web servers, databases, programming languages, and development frameworks. No matter what combination of technologies you prefer to work with, there is an integrated development environment (IDE) that can increase your productivity: Eclipse. In this tutorial, Part 1 of a three-part "Web development with Eclipse Europa" series on how to use Eclipse for Web development with Java technology, PHP, and Ruby, we'll see how the latest release of Eclipse -- Europa -- can be used to rapidly develop Java Web applications. We'll use Java Platform, Enterprise Edition 5 (Java EE) for Eclipse to build a Web application for tracking and calculating baseball statistics.
    FREE! Go There Now!


    NEW! Webcast: Extreme transaction processing with WebSphere Extended Deployment

    In this webcast, you'll get an introduction to the eXtreme Transaction Processing (XTP) features of WebSphere Extended Deployment and the common architectural traits required by XTP applications. See how WebSphere Extended Deployment's ObjectGrid feature provides a state-of-the-art infrastructure for hosting XTP applications.
    FREE! Go There Now!


    NEW! Webcast: Quickly provide customized, integrated user interfaces with Lotus Notes 8

    IBM Lotus Notes 8 provides a wide range of developers the ability to provide customized, integrated user interfaces via composite applications and via custom sidebar and toolbar plug-ins. This webcast provides you with tips and techniques to use with out-of-the-box capabilities of Lotus Notes 8, and survey how you can share useful components within your own company and within a larger community.
    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