Figure 3-10V isually Removing Items from a Collection The DropDownList, ListBox, CheckBoxList, and RadioButtonList server controls give you the capability to visually remove items from t
Trang 1Figure 3-10
V isually Removing Items from a Collection
The DropDownList, ListBox, CheckBoxList, and RadioButtonList server controls give you the capability
to visually remove items from the collection displayed in the control, although you can still work with
the items that are not displayed in your server-side code
The ListBox, CheckBoxList, and RadioButtonList controls are discussed shortly in this chapter.
For a quick example of removing items, create a drop-down list with three items, including one that
you will not display On the postback, however, you can still work with the ListItem’sValueorText
property, as illustrated in Listing 3-11
Listing 3-11: Disabling certain ListItems from a collection
VB
<%@ page language="VB" %>
<script runat="server">
Protected Sub DropDownList1_SelectedIndexChanged(ByVal sender As Object, _
ByVal e As System.EventArgs)
Response.Write("You selected item number " & _ DropDownList1.SelectedValue & "<br>")
Response.Write("You didn’t select item number " & _ DropDownList1.Items(1).Value)
End Sub
</script>
<html>
<head runat="server">
<title>DropDownList Server Control</title>
</head>
<body>
<form id="form1" runat="server">
Trang 2<asp:DropDownList ID="DropDownList1" Runat="server" AutoPostBack="True"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
<asp:ListItem Value="1">First Choice</asp:ListItem>
<asp:ListItem Value="2" Enabled="False">Second Choice</asp:ListItem>
<asp:ListItem Value="3">Third Choice</asp:ListItem>
</asp:DropDownList>
</form>
</body>
</html>
C#
<%@ Page Language="C#" %>
<script runat="server">
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
Response.Write("You selected item number " + DropDownList1.SelectedValue + "<br>");
Response.Write("You didn’t select item number " + DropDownList1.Items[1].Value);
}
</script>
From the code, you can see that the<asp:ListItem>element has an attribute:Enabled The Boolean
value given to this element dictates whether an item in the collection is displayed If you useEnabled=" False", the item is not displayed, but you still have the capability to work with the item in the server-side code displayed in theDropDownList1_SelectedIndexChangedevent The result of the output from these
Response.Writestatements is shown in Figure 3-11
Figure 3-11
The ListBox Ser ver Control
The ListBox server control has a function similar to the DropDownList control It displays a collection
of items The ListBox control behaves differently from the DropDownList control in that it displays
Trang 3more of the collection to the end user, and it enables the end user to make multiple selections from the
collection — something that is not possible with the DropDownList control
A typical ListBox control appears in code as follows:
<asp:ListBox ID="ListBox1" runat="server">
<asp:ListItem>Hematite</asp:ListItem>
<asp:ListItem>Halite</asp:ListItem>
<asp:ListItem>Limonite</asp:ListItem>
<asp:ListItem>Magnetite</asp:ListItem>
</asp:ListBox>
This generates the browser display illustrated in Figure 3-12
Figure 3-12
Allowing Users to Select Multiple Items
You can use theSelectionModeattribute to let your end users make multiple selections from what is
displayed by the ListBox control Here’s an example:
<asp:ListBox ID="ListBox1" runat="server" SelectionMode="Multiple">
<asp:ListItem>Hematite</asp:ListItem>
<asp:ListItem>Halite</asp:ListItem>
<asp:ListItem>Limonite</asp:ListItem>
<asp:ListItem>Magnetite</asp:ListItem>
</asp:ListBox>
The possible values of theSelectionModeproperty includeSingleandMultiple Setting the value to
Multipleallows the end user to make multiple selections in the list box The user must hold down either
the Ctrl or Shift keys while making selections Holding down the Ctrl key enables the user to make a
single selection from the list while maintaining previous selections Holding down the Shift key enables
a range of multiple selections
An Example of Using the ListBox Control
The ListBox control shown in Listing 3-12 allows multiple selections to be displayed in the browser when
a user clicks the Submit button The form should also have an additional text box and button at the top
that enables the end user to add additional items to the ListBox
Listing 3-12: Using the ListBox control
VB
<%@ Page Language="VB" %>
Continued
Trang 4<script runat="server">
Protected Sub Button1_Click(ByVal sender As Object, _
ByVal e As System.EventArgs)
ListBox1.Items.Add(TextBox1.Text.ToString())
End Sub
Protected Sub Button2_Click(ByVal sender As Object, _
ByVal e As System.EventArgs)
Label1.Text = "You selected from the ListBox:<br>"
For Each li As ListItem In ListBox1.Items
If li.Selected = True Then
label1.Text += li.Text & "<br>"
End If
Next
End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Using the ListBox</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Add an additional item"
OnClick="Button1_Click" /><br /><br />
<asp:ListBox ID="ListBox1" runat="server" SelectionMode="multiple">
<asp:ListItem>Hematite</asp:ListItem>
<asp:ListItem>Halite</asp:ListItem>
<asp:ListItem>Limonite</asp:ListItem>
<asp:ListItem>Magnetite</asp:ListItem>
</asp:ListBox><br /><br />
<asp:Button ID="Button2" runat="server" Text="Submit"
OnClick="Button2_Click" /><br /><br />
<asp:Label ID="Label1" runat="server"></asp:Label>
</div>
</form>
</body>
</html>
C#
<%@ Page Language="C#" %>
<script runat="server">
protected void Button1_Click(object sender, EventArgs e)
Continued
Trang 5ListBox1.Items.Add(TextBox1.Text.ToString());
}
protected void Button2_Click(object sender, EventArgs e)
{
Label1.Text = "You selected from the ListBox:<br>";
foreach (ListItem li in ListBox1.Items) {
if (li.Selected) { Label1.Text += li.Text + "<br>";
} }
}
</script>
This is an interesting example First, some default items (four common minerals) are already placed inside
the ListBox control However, the text box and button at the top of the form allow the end user to add
additional minerals to the list Users can then make one or more selections from the ListBox, including
selections from the items that they dynamically added to the collection After a user makes his selection
and clicks the button, theButton2_Clickevent iterates through theListIteminstances in the collection
and displays only the items that have been selected
This control works by creating an instance of aListItemobject and using itsSelectedproperty to see
if a particular item in the collection has been selected The use of theListItemobject is not limited
to the ListBox control (although that is what is used here) You can dynamically add or remove items
from a collection and get at items and their values using theListItemobject in the DropDownList,
CheckBoxList, and RadioButtonList controls as well It is a list-control feature
When this page is built and run, you get the results presented in Figure 3-13
Figure 3-13
Trang 6Adding Items to a Collection
To add items to the collection, you can use the following short syntax:
ListBox1.Items.Add(TextBox1.Text)
Look at the source code created in the browser, and you should see something similar to the following
generated dynamically:
<select size="4" name="ListBox1" multiple="multiple" id="ListBox1">
<option value="Hematite">Hematite</option>
<option value="Halite">Halite</option>
<option value="Limonite">Limonite</option>
<option value="Magnetite">Magnetite</option>
<option value="Olivine">Olivine</option>
</select>
You can see that the dynamically added value is a text item, and you can see its value You can also add instances of the ListItem object to get different values for the item name and value:
VB
ListBox1.Items.Add(New ListItem("Olivine", "MG2SIO4"))
C#
ListBox1.Items.Add(new ListItem("Olivine", "MG2SIO4"));
This example adds a new instance of theListItemobject — adding not only the textual name of the item, but also the value of the item (its chemical formula) It produces the following results in the browser:
<option value="MG2SIO4">Olivine</option>
The CheckBox Ser ver Control
Check boxes on a Web form enable your users to either make selections from a collection of items or
specify a value of an item to be yes/no, on/off, or true/false Use either the CheckBox control or the
CheckBoxList control to include check boxes in your Web forms
The CheckBox control allows you to place single check boxes on a form; the CheckBoxList control allows you to place collections of check boxes on the form You can use multiple CheckBox controls on your
ASP.NET pages, but then you are treating each check box as its own element with its own associated
events On the other hand, the CheckBoxList control allows you to take multiple check boxes and create specific events for the entire group
Listing 3-13 shows an example of using the CheckBox control
Listing 3-13: Using a single instance of the CheckBox control
VB
<%@ Page Language="VB" %>
Continued
Trang 7<script runat="server">
Protected Sub CheckBox1_CheckedChanged(ByVal sender As Object, _
ByVal e As System.EventArgs)
Response.Write("Thanks for your donation!") End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>CheckBox control</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:CheckBox ID="CheckBox1" runat="server" Text="Donate $10 to our cause!"
OnCheckedChanged="CheckBox1_CheckedChanged" AutoPostBack="true" />
</div>
</form>
</body>
</html>
C#
<%@ Page Language="C#" %>
<script runat="server">
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
Response.Write("Thanks for your donation!");
}
</script>
This produces a page that contains a single check box asking for a monetary donation Using the
Checked-Changedevent,OnCheckedChangedis used within the CheckBox control The attribute’s value points to
theCheckBox1_CheckedChangedevent, which fires when the user checks the check box It occurs only
if theAutoPostBackproperty is set toTrue(this property is set toFalseby default) Running this page
produces the results shown in Figure 3-14
Figure 3-14
Trang 8How to Determine Whether Check Boxes Are Checked
You might not want to use theAutoPostBackfeature of the check box, but instead want to determine if the check box is checked after the form is posted back to the server You can make this check through an
If Thenstatement, as illustrated in the following example:
VB
If (CheckBox1.Checked = True) Then
Response.Write("CheckBox is checked!")
End If
C#
if (CheckBox1.Checked == true) {
Response.Write("Checkbox is checked!");
}
This check is done on the CheckBox value using the control’sCheckedproperty The property’s value is
a Boolean value, so it is eitherTrue(checked) orFalse(not checked)
Assigning a Value to a Check Box
You can also use theCheckedproperty to make sure a check box is checked based on other dynamic
values:
VB
If (Member = True) Then
CheckBox1.Checked = True
End If
C#
if (Member == true) {
CheckBox1.Checked = true;
}
Aligning Text Around the Check Box
In the previous check box example, the text appears to the right of the actual check box, as shown in
Figure 3-15
Figure 3-15 Using the CheckBox control’sTextAlignproperty, you can realign the text so that it appears on the other side of the check box:
<asp:CheckBox ID="CheckBox1" runat="server" Text="Donate $10 to our cause!"
OnCheckedChanged="CheckBox1_CheckedChanged" AutoPostBack="true"
TextAlign="Left" />
The possible values of theTextAlignproperty are eitherRight(the default setting) orLeft This property
is also available to the CheckBoxList, RadioButton, and RadioButtonList controls Assigning the value
Trang 9Figure 3-16
The CheckBoxList Ser ver Control
The CheckBoxList server control is quite similar to the CheckBox control, except that the former enables
you to work with a collection of items rather than a single item The idea is that a CheckBoxList server
control instance is a collection of related items, each being a check box unto itself
To see the CheckBoxList control in action, you can build an example that uses Microsoft’s SQL Server to
pull information from the Customers table of the Northwind example database An example is presented
in Listing 3-14
Listing 3-14: Dynamically populating a CheckBoxList
VB
<%@ Page Language="VB" %>
<script runat="server">
Protected Sub Button1_Click(ByVal sender As Object, _
ByVal e As System.EventArgs)
Label1.Text = "You selected:<br>"
For Each li As ListItem In CheckBoxList1.Items
If li.Selected = True Then Label1.Text += li.Text & "<br>"
End If Next End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>CheckBoxList control</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Submit Choices"
OnClick="Button1_Click" /><br /><br />
<asp:Label ID="Label1" runat="server"></asp:Label>
<br />
<asp:CheckBoxList ID="CheckBoxList1" runat="server"
DataSourceID="SqlDataSource1" DataTextField="CompanyName"
RepeatColumns="3" BorderColor="Black"
BorderStyle="Solid" BorderWidth="1px">
</asp:CheckBoxList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
SelectCommand="SELECT [CompanyName] FROM [Customers]"
ConnectionString="<%$ ConnectionStrings:AppConnectionString1 %>">
</asp:SqlDataSource>
Trang 10</form>
</body>
</html>
C#
<%@ Page Language="C#" %>
<script runat="server">
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "You selected:<br>";
foreach (ListItem li in CheckBoxList1.Items) {
if (li.Selected == true) {
Label1.Text += li.Text + "<br>";
}
}
}
</script>
This ASP.NET page has a SqlDataSource control on the page that pulls the information you need from the Northwind database From theSELECTstatement used in this control, you can see that you are retrieving theCompanyNamefield from each of the listings in the Customers table
The CheckBoxList control binds itself to the SqlDataSource control using a few properties:
<asp:CheckBoxList ID="CheckBoxList1" runat="server"
DataSourceID="SqlDataSource1" DataTextField="CompanyName"
RepeatColumns="3" BorderColor="Black"
BorderStyle="Solid" BorderWidth="1px">
</asp:CheckBoxList>
TheDataSourceIDproperty is used to associate the CheckBoxList control with the results that come
back from the SqlDataSource control Then theDataTextFieldproperty is used to retrieve the name of the field you want to work with from the results In this example, it is the only one that is available: the
CompanyName That’s it! CheckBoxList generates the results you want
The remaining code consists of styling properties, which.are pretty interesting TheBorderColor,
Bor-derStyle, andBorderWidthproperties enable you to put a border around the entire check box list The most interesting property is theRepeatColumnsproperty, which specifies how many columns (three in
this example) can be used to display the results
When you run the page, you get the results shown in Figure 3-17
TheRepeatDirectionproperty instructs the CheckBoxList control about how to lay out the items bound
to the control on the Web page Possible values includeVerticalandHorizontal The default value is
Vertical Setting it toVerticalwith aRepeatColumnsetting of3gives the following results:
CheckBox1 CheckBox5 CheckBox9
CheckBox2 CheckBox6 CheckBox10
CheckBox3 CheckBox7 CheckBox11
CheckBox4 CheckBox8 CheckBox12