codetoad.com
  ASP Shopping CartForum & BBS
  - all for $20 from CodeToad Plus!
  
  Home || ASP | ASP.Net | C++/C# | DHTML | HTML | Java | Javascript | Perl | VB | XML || CodeToad Plus! || Forums || RAM 
Search Site:



Home » ASP » Article

ASP.NET : The listbox control

Article by: David Sussman, et al (7/8/2002)
Bookmark us now! Add to Favourites
Email a friend!Tell a friend
Summary: The next HTML server control that we'll look at, <asp:listbox>, is very much related to <asp:dropdownlist>.
Viewed: 188559 times Rating (5 votes): 
 3.4 out of 5
 Rate this Article  Read Comments  Post Comments


Previous Page  Page 1 Page 2 Page 3 Page 4 Page 5 Page 6 Page 7 Page 8  Page 10 Page 11 Page 12 Page 13 Next Page  

The <asp:listbox> Control

The next HTML server control that we'll look at, <asp:listbox>, is very much related to <asp:dropdownlist>. In fact, we've almost mentioned it already. Remember the <select> HTML form control that creates drop-down listboxes? Well, the <asp:listbox> is a server-side equivalent of using that <select> tag with the size attribute set to the maximum number of options possible. In fact the only difference with this control is the fact that it doesn't drop down, and that it is capable of multiple selections.

 

The <asp:listbox> has the following format:

 

<asp:listbox id="list1" runat="server" selection mode = "multiple">

  <asp:listitem>Madrid</asp:listitem >

  <asp:listitem >Oslo</asp:listitem >

  <asp:listitem >Lisbon</asp:listitem >

</asp:listbox>

 

There is one point of interest, however: the selectionmode attribute is used to determine whether you can select multiple or only single items from the listbox. By default, it is set to single, but you have the option to change it.

 

Let's take a look at a quick example, where we alter our previous example to use a listbox instead of a drop-down list control. We'll also alter it to allow multiple selections.

Try It Out – Using the <asp:listbox> Control

1.       Enter the following code into your editor:

 

<script runat="server" language="C#">

    void Page_Load()

    { 

  string msg = "You have selected: <br />";

 

      if (list1.Items[0].Selected) {

    msg = msg + list1.Items[0].Text + "<br />";


  }

        if (list1.Items[1].Selected) { 

     msg = msg + list1.Items[1].Text + "<br />";

  }

        if (list1.Items[2].Selected) {

    msg = msg + list1.Items[2].Text + "<br />";

  }

     Message.Text = msg;

    }

</script>

<html>

  <head>

    <title>Drop Down List Example</title>

  </head>

  <body>

    <asp:label id="Message" runat="server"/>

    <br />

    <form runat="server">

    Which city do you wish to look at hotels for?<br /><br />

    <asp:listbox id="list1" runat="server" selectionmode="multiple">

      <asp:listitem>Madrid</asp:listitem>

      <asp:listitem>Oslo</asp:listitem>

      <asp:listitem>Lisbon</asp:listitem>

    </asp:listbox>

    <br /><br /><br /><br />

    <input type="Submit">

    </form>

  </body>

</html>

 

2.       Save this as listpage2.aspx.

3.       Run this page in your browser, and use the Ctrl, or shift keys to select multiple choices:


 

4.       Click on Submit Query to see the following:

 

How It Works

The controls in this example have hardly changed from the previous listpage.aspx example. All we've done is add a selectionmode attribute to allow us to make multiple selections:

 

<asp:listbox id="list1" runat="server" selectionmode="multiple">

  <asp:listitem>Madrid</asp:listitem>

  <asp:listitem>Oslo</asp:listitem>

  <asp:listitem>Lisbon</asp:listitem>

</asp:listbox>

 

However, we've had to completely overhaul our ASP.NET code:

 

    string msg = "You have selected: <br />";

 

      if (list1.Items[0].Selected) {

    msg = msg + list1.Items[0].Text + "<br />";

  }

        if (list1.Items[1].Selected) { 

     msg = msg + list1.Items[1].Text + "<br />";

  }


        if (list1.Items[2].Selected) {

    msg = msg + list1.Items[2].Text + "<br />";

  }

     Message.Text = msg;

 

In fact, we've introduced a whole new format to determine the options to display.

 

We use an If construct (we'll talk more about these in Chapter 6) to determine which items have been selected, and then use a variable assignment to create the display output. The first line in our code creates a String variable (again, we'll be looking at variables in depth very shortly). This simply declares a label 'msg' which refers to a portion in the computer's memory that we can use to hold a sequence of characters, or string. We set it up with a simple heading, and then add city names on the end, according to which list elements have been selected. Finally, we assign its final value (a long string of HTML) to the Text attribute of the Message label, so that it can be seen on the page.

 

That was a bit more complicated, wasn't it? Don't worry, it will become clearer once you've familiarized yourself with the topics in the following few chapters. For now, let's move on to some different types
of control.

Previous Page  Page 1 Page 2 Page 3 Page 4 Page 5 Page 6 Page 7 Page 8  Page 10 Page 11 Page 12 Page 13 Next Page  




Click here to Buy!

Buy Beginning ASP.NET with C# here

© Copyright 2002 Wrox Press This chapter is written by David Sussman, et al and taken from "Beginning ASP.NET with C#" published by Wrox Press Limited in June 2002; ISBN 1861007345; copyright © Wrox Press Limited 2002; all rights reserved.

No part of these chapters may be reproduced, stored in a retrieval system or transmitted in any form or by any means -- electronic, electrostatic, mechanical, photocopying, recording or otherwise -- without the prior written permission of the publisher, except in the case of brief quotations embodied in critical articles or reviews.






CodeToad Experts

Can't find the answer?
Our Site experts are answering questions for free in the CodeToad forums
Rate this article:     Poor Excellent
View highlighted Comments
User Comments on 'ASP.NET : The listbox control'
Posted by :  Archive Import (srinivas) at 00:51 on Sunday, November 24, 2002
How can i find the number of elements in a List Box in ASP.NET
Posted by :  Archive Import (vidyadhar) at 07:54 on Thursday, February 13, 2003
how can i get horzinital scroll bar to list box .u plz help me out from this problem.

vidyadhar
Posted by :  Archive Import (Lingo Martini) at 13:30 on Tuesday, September 16, 2003
Great tutorial!

Just in case you want to cut down on the syntax a little bit, add the value to each list item:

<asp:listbox ID="payment_type" Rows="2" runat="server" SelectionMode="single"> <asp:ListItem value="CC">Credit Card</asp:ListItem>
<asp:ListItem value="ECHECK">E-Check</asp:ListItem>
</asp:radiobuttonlist>


Then you can simply access the value of the selected item:

lblMessage.Text = payment_type.SelectedItem.Value;


Of course, there are situations in which it is necessary to use the If... statements as shown in the tutorial.

For what it's worth,

Lingo Martini

Posted by :  yogesh_singh_rana at 08:42 on Friday, April 08, 2005
how can i get horzinital scroll bar to list box .u plz help me out from this problem.and this is in asp.net
please give the quick answer

YOGESH
Posted by :  demarie at 08:59 on Tuesday, April 19, 2005
How do I, upon page load, automatically [u] scroll [/u] to a listbox value without highlighting it? For example, when my form loads and displays on the screen, I want the 3rd value (or index value 2) in the listbox list to display in the listbox field without any highlighting. Basically the listbox field needs to default to this value when the page is loaded.
Posted by :  inderpal0 at 02:47 on Tuesday, May 03, 2005
can we select multiples options in a list box control without using control key like we have a control in VB6 and in that if we set the mutiselect property to 1-Simple, then we can select multiple options without using control key.......

Cheers
Inderpal
Posted by :  izhar.khan@palcom.net at 06:49 on Wednesday, August 02, 2006
I too got a better view after reading this article !!
Posted by :  izhar.khan@palcom.net at 06:06 on Thursday, August 03, 2006
[b]iouio[/b]
Posted by :  PeterBrunone at 11:30 on Wednesday, January 10, 2007
inderpal0, there are some controls that do this like EasyListBox ( see http://easylistbox.com/demoMulti.aspx?rl=ctf ); also, I have a recent article at http://tinyurl.com/yxfslj that will do the same thing.

Cheers,

Peter

<Added>

So much for automatically converting to links... here's the longer version for the article in case the tinyurl expires:

http://blogs.aspfriends.com/afblogs/blogs/insightaspnet/archive/2007/01/09/CTRL-Freaks_3A00_--the-Psychology-of-a-ListBox.aspx
Posted by :  PeterBrunone at 11:31 on Wednesday, January 10, 2007
and the ELB link:

http://easylistbox.com/demoMulti.aspx?rl=ctf

<Added>

ARGH

http://easylistbox.com/demoMulti.aspx?rl=ctf
Posted by :  Instant Activation Hosting at 05:22 on Monday, May 18, 2009
When i need right click selection for some list controls i'm just using List view control instead of list Box.Can't see any reason why to write any additional code.Simplicity must be kept in everything!

http://www.marblehost.com/how-long-does-it-take-for-my-account-to-be-setup-after-signing-up.php
Posted by :  Instant Activation Hosting at 05:24 on Monday, May 18, 2009
Suppose I have numeric values in my listbox. How do I add them and display the result on a message box.
<a href="http://www.marblehost.com/how-long-does-it-take-for-my-account-to-be-setup-after-signing-up.php">http://www.marblehost.com/how-long-does-it-take-for-my-account-to-be-setup-after-signing-up.php</a>



<Added>

http://www.marblehost.com/how-long-does-it-take-for-my-account-to-be-setup-after-signing-up.php
Posted by :  Instant Activation Hosting at 05:29 on Monday, May 18, 2009
How to lock particular item in the list box in visual basic?
[quote]http://www.marblehost.com/how-long-does-it-take-for-my-account-to-be-setup-after-signing-up.php[/quote]


<Added>

http://www.marblehost.com/how-long-does-it-take-for-my-account-to-be-setup-after-signing-up.php
Posted by :  Instant Activation Hosting at 22:55 on Monday, May 18, 2009
Oh, that's right... you need a using statement in your page. I forgot to put that in, I'll fix the article. just add the following to your using statements to the page. using System.Collections.Generic;

<Added>

http://www.marblehost.com/how-long-does-it-take-for-my-account-to-be-setup-after-signing-up.php

<Added>

I believe ViewState["myControlList"] = myControlList; should be outside if(IsPostBack) else it will remain null on postbacks.

http://www.marblehost.com/how-long-does-it-take-for-my-account-to-be-setup-after-signing-up.php


To post comments you need to become a member. If you are already a member, please log in .

 



RELATED ARTICLES
ASP FilesystemObject
by Jeff Anderson
An introduction to the Filesystemobject
ASP GetTempName
by Jeff Anderson
Use the GetTempName method to create a randomly generated temporary file on the server.
ASP OpenTextFile
by Jeff Anderson
An introduction to the OpenTextFile Method of the FileSystemObject
ASP Format Date and Time Script
by Jeff Anderson
An ASP script showing the variety of date and time formats possible using the FormatDateTime Function.
Email validation using Regular Expression
by Jeff Anderson
Using regular expression syntax is an exellent way to thoroughly validate an email. It's possible in ASP.
Creating a Dynamic Reports using ASP and Excel
by Jeff Anderson
A simple way to generate Excel reports from a database using Excel.
Concatenate strings in sql
by Jeff Anderson
A brief introduction to concatenating strings in an sql query (using SQL server or access databases).
ASP FileExists
by Jeff Anderson
An introduction to the FileExistsMethod of the FileSystemObject
Creating an SQL Trigger
by Jeff Anderson
A beginners guide to creating a Trigger in SQL Server
Create an ASP SQL Stored Procedure
by Jeff Anderson
A beginners guide to setting up a stored procedure in SQL server and calling it from an ASP page.








Recent Forum Threads
• Regular Expression Query Replace -- Twice Wrongly
• Processing MS Office documents with Java
• Re: help!
• Re: Can javascript preload swf files?
• ADODB.Recordset error (0x800A0CB3)
• Need Your Inputs About Level Editor Interface
• `section` is an unexpected token. Expecting white space. Line 1, position 137.
• Javascript rollover toggle help please!
• help monitoting cpu load on windows machine


Recent Articles
ASP GetTempName
Decode and Encode UTF-8
ASP GetFile
ASP FolderExists
ASP FileExists
ASP OpenTextFile
ASP FilesystemObject
ASP CreateFolder
ASP CreateTextFile
Javascript Get Selected Text


© Copyright codetoad.com 2001-2009