Download
Academy
Current location: Downcodes.com -> Academy -> Programming -> .NET tutorial -> Using the ASP.NET 2.0 ListBox Control(2)
Recommend
HOT TOP10
Using the ASP.NET 2.0 ListBox Control(2)
Date: 2008-1-4 Author: Hit: View:[Large font Middle font Small font]
Adding Items Programmatically
(Page 2 of 5 )

Delete this ListBox control and add another one to the page, or simply clear out the ListItem elements of the control's markup. Check the Enable AutoPostBack checkbox from the task menu as shown in the next screen shot.

Also set the Width and Height of the ListBox Control through the Properties window (or you can do it through the markup code) as shown below.

Write the following code in the Page_Load() event handler method.

 // checking if this page is loading for the first item or it's

// postback. If it's not a postback and the page is loading for

// the first time then we populate the ListBox control with the

// Listitem objects and if it's a PostBack we simply do nothing

  if (!IsPostBack)

{

//creating the ListItem objects

  ListItem firstItem = new ListItem();

   firstItem.Text = "Mick Joseph";

   firstItem.Value = "10";

  ListItem secondItem = new ListItem();

    secondItem.Text = "Mary Johnson";

    secondItem.Value = "11";

  ListItem thirdItem = new ListItem();

  thirdItem.Text = "David Johnson";

   thirdItem.Value = "12";

  ListItem FourthItem = new ListItem();

   FourthItem.Text = "Mark Roberts";

    FourthItem.Value = "13";

  ListItem FifthItem = new ListItem();

   FifthItem.Text = "Paul Bill";

   FifthItem.Value = "14";

// adding the ListItem objects to the Item collection of the

ListBox Control

  ListBox1.Items.Add(firstItem);

  ListBox1.Items.Add(secondItem);
 

  ListBox1.Items.Add(thirdItem);

  ListBox1.Items.Add(FourthItem);

  ListBox1.Items.Add(FifthItem);

And the markup of the ListBox control looks like this:

<asp:ListBox ID="ListBox1" runat="server" AutoPostBack="True"
Height="100px" Width="100px"></asp:ListBox>

When you run the page you can select another item and the page will post back to the server. For now we don't do anything when posting back. The page looks like the following screen shot:

Next we'll take a look at what we just did with the above code.

(From: aspfree)

Relative article:
·Using the ASP.NET 2.0 ListBox Control(1)
·Using the ASP.NET 2.0 ListBox Control(3)
·Using the ASP.NET 2.0 ListBox Control(4)
·Using the ASP.NET 2.0 ListBox Control(5)
Relative software: