.NET Framework Class Library ListItem Class Represents a data item in a data-bound list control. This class cannot be inherited.

Inheritance Hierarchy
Namespace:
System.Web.UI.WebControls
Assembly:
System.Web (in System.Web.dll)

Syntax
<TypeConverterAttribute(GetType(ExpandableObjectConverter))> _
Public NotInheritable Class ListItem _
Implements IStateManager, IParserAccessor, IAttributeAccessor
[TypeConverterAttribute(typeof(ExpandableObjectConverter))]
public sealed class ListItem : IStateManager,
IParserAccessor, IAttributeAccessor
[TypeConverterAttribute(typeof(ExpandableObjectConverter))]
public ref class ListItem sealed : IStateManager,
IParserAccessor, IAttributeAccessor
[<Sealed>]
[<TypeConverterAttribute(typeof(ExpandableObjectConverter))>]
type ListItem =
class
interface IStateManager
interface IParserAccessor
interface IAttributeAccessor
end
The ListItem type exposes the following members.

Constructors

Methods

Explicit Interface Implementations

Remarks
A ListItem control represents an individual data item within a data-bound list control, such as a ListBox or a RadioButtonList control. There are several ways to specify the text displayed for an item in the list control. The most common method is by placing text in the inner HTML content. The inner HTML content is the text between the opening and closing tags of the ListItem control. You can also use the Text property to specify the text displayed in the list control for the item. The Value property allows you to associate a value with the item in the list control, in addition to the text displayed in the control. For example, you can display text for an item in the list control, such as "Item 1", and use the Value property to specify a value for that item, such as "$1.99". You can have any combination of the inner HTML content, Text, or Value properties set. The resulting HTML output for the ListItem control depends on the combination of these three properties that are set. For example, if all three properties are set as follows:
<asp:ListItem Value="Value 1" Text="Item 1">Inner 1</asp:ListItem>
The inner HTML content is used for rendered inner HTML content and the Value property is used for the Value attribute. The resulting HTML rendering output is:
<option value="Value 1">Inner 1</option>
The following table lists the combination of set properties and the corresponding property used for the rendered inner HTML content and Value attribute. The three columns on the left list the combination of set properties. The two columns on the right list which property value is used for the corresponding attribute. Inner HTML content | Text property | Value property | Rendered Inner HTML content | Rendered Value attribute |
|---|
Set | Set | Set | Inner HTML content | Value property | Set | Set | Not set | Inner HTML content | Inner HTML content | Set | Not set | Set | Inner HTML content | Value property | Set | Not set | Not set | Inner HTML content | Inner HTML text | Not set | Set | Set | Text property | Value property | Not set | Set | Not set | Text property | Text property | Not set | Not set | Set | Value property | Value property | Not set | Not set | Not set | Not set | Not set |
Note |
|---|
Because the Text and Value properties each have a default value of an empty string, it is possible to have empty list items in the list control. |
When a list control is displayed, any ListItem control with its Selected property set to true appears highlighted in the control. The ListItem control provides the Enabled property to allow you to specify whether a ListItem control is enabled or disabled. A ListItem control that is disabled is dimmed to indicate that it cannot be selected. Use this property to disable a ListItem control in either a RadioButtonList control or a CheckBoxList control. Note |
|---|
You cannot use this property to disable a ListItem control in a DropDownList control or ListBox control. |
For a list of initial property values for an instance of ListItem, see the ListItem constructor.

Examples
The following example illustrates the use of ListItem controls within a ListBox control. Note |
|---|
The following code samples use the single-file code model and may not work correctly if copied directly into a code-behind file. Each code sample must be copied into an empty text file that has an .aspx extension. For more information on the Web Forms code model, see ASP.NET Web Page Code Model. |
<%@ Page Language="VB" AutoEventWireup="True" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html >
<head>
<title>ListBox Example</title>
<script language="VB" runat="server">
Sub SubmitBtn_Click(Sender As Object, e As EventArgs)
If ListBox1.SelectedIndex > -1 Then
Label1.Text = "You chose: " & ListBox1.SelectedItem.Text
Label1.Text &= "<br /> with value: " & ListBox1.SelectedItem.Value
End If
End Sub
</script>
</head>
<body>
<h3>ListBox Example</h3>
<br />
<form id="form1" runat="server">
<asp:ListBox id="ListBox1" Width="100px" runat="server">
<asp:ListItem>Item 1</asp:ListItem>
<asp:ListItem>Item 2</asp:ListItem>
<asp:ListItem>Item 3</asp:ListItem>
<asp:ListItem Value="Value 4">Item 4</asp:ListItem>
<asp:ListItem Text="Item 5" Value="Value 5" Selected="True"/>
<asp:ListItem>Item 6</asp:ListItem>
</asp:ListBox>
<asp:button Text="Submit" OnClick="SubmitBtn_Click" runat="server" />
<br />
<asp:Label id="Label1" font-names="Verdana" font-size="10pt" runat="server"/>
</form>
</body>
</html>
<%@ Page Language="C#" AutoEventWireup="True" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html >
<head>
<title>ListBox Example</title>
<script language="C#" runat="server">
void SubmitBtn_Click(Object Sender, EventArgs e) {
if (ListBox1.SelectedIndex > -1) {
Label1.Text="You chose: " + ListBox1.SelectedItem.Text;
Label1.Text+="<br /> with value: " + ListBox1.SelectedItem.Value;
}
}
</script>
</head>
<body>
<h3>ListBox Example</h3>
<br />
<form id="form1" runat="server">
<asp:ListBox id="ListBox1" Width="100px" runat="server">
<asp:ListItem>Item 1</asp:ListItem>
<asp:ListItem>Item 2</asp:ListItem>
<asp:ListItem>Item 3</asp:ListItem>
<asp:ListItem Value="Value 4">Item 4</asp:ListItem>
<asp:ListItem Text="Item 5" Value="Value 5" Selected="True"/>
<asp:ListItem>Item 6</asp:ListItem>
</asp:ListBox>
<asp:button Text="Submit" OnClick="SubmitBtn_Click" runat="server" />
<br />
<asp:Label id="Label1" font-names="Verdana" font-size="10pt" runat="server"/>
</form>
</body>
</html>
<!-- This example demonstrates how to select multiple items from a DataList
and add the selected items to a DataGrid. The example uses a For Each loop
to iterate through the ListItem objects in the ListItemCollection of ListBox1. -->
...
<%@ Page language="VB" AutoEventWireup="true"%>
<%@ Import Namespace="System.Data" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
' Global Variables.
Private dv As DataView
Private dt As New DataTable()
Private Sub Page_Load(sender As Object, e As System.EventArgs)
' Set the number of rows displayed in the ListBox to be
' the number of items in the ListBoxCollection.
ListBox1.Rows = ListBox1.Items.Count
' If the DataTable is already stored in the Web form's default
' HttpSessionState variable, then don't recreate the DataTable.
If Session("data") Is Nothing Then
' Add columns to the DataTable.
dt.Columns.Add(New DataColumn("Item"))
dt.Columns.Add(New DataColumn("Price"))
' Store the DataTable in the Session variable so it can be
' accessed again later.
Session("data") = dt
' Use the table to create a DataView, because the DataGrid
' can only bind to a data source that implements IEnumerable.
dv = New DataView(dt)
' Set the DataView as the data source, and bind it to the DataGrid.
DataGrid1.DataSource = dv
DataGrid1.DataBind()
End If
End Sub
Private Sub addButton_Click(sender As Object, e As System.EventArgs)
' Add the items selected in ListBox1 to DataGrid1.
Dim item As ListItem
For Each item In ListBox1.Items
If item.Selected Then
' Add the item to the DataGrid.
' First, get the DataTable from the Session variable.
dt = CType(Session("data"), DataTable)
If Not (dt Is Nothing) Then
' Create a new DataRow in the DataTable.
Dim dr As DataRow
dr = dt.NewRow()
' Add the item to the new DataRow.
dr("Item") = item.Text
' Add the item's value to the DataRow.
dr("Price") = item.Value
' Add the DataRow to the DataTable.
dt.Rows.Add(dr)
' Rebind the data to DataGrid1.
dv = new DataView(dt)
DataGrid1.DataSource = dv
DataGrid1.DataBind()
End If
End If
Next item
End Sub
</script>
<html >
<head>
<title> ListItemCollection Example </title>
</head>
<body>
<form id="form1" runat="server">
<h3> ListItemCollection Example </h3>
<table cellpadding="6" border="0">
<tr>
<td valign="top">
<asp:ListBox id="ListBox1" runat="server" SelectionMode="Multiple">
<asp:ListItem Value=".89">apples</asp:ListItem>
<asp:ListItem Value=".49">bananas</asp:ListItem>
<asp:ListItem Value="2.99">cherries</asp:ListItem>
<asp:ListItem Value="1.49">grapes</asp:ListItem>
<asp:ListItem Value="2.00">mangos</asp:ListItem>
<asp:ListItem Value="1.09">oranges</asp:ListItem>
</asp:ListBox>
</td>
<td valign="top">
<asp:Button id="addButton" runat="server" Text="Add -->"
Width="100px" OnClick="addButton_Click"></asp:Button>
</td>
<td valign="top">
<asp:DataGrid Runat="server" ID="DataGrid1" CellPadding="4">
</asp:DataGrid>
</td>
</tr>
</table>
</form>
</body>
</html>
<!-- This example demonstrates how to select multiple items from a DataList and add the
selected items to a DataGrid. The example uses a foreach loop to iterate through
the ListItem objects in the ListItemCollection of ListBox1. -->
...
<%@ Page language="c#" AutoEventWireup="true"%>
<%@ Import Namespace="System.Data" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script language="C#" runat="server">
// Global Variables.
private DataView dv;
private DataTable dt = new DataTable();
private void Page_Load(object sender, System.EventArgs e)
{
// Set the number of rows displayed in the ListBox to be
// the number of items in the ListBoxCollection.
ListBox1.Rows = ListBox1.Items.Count;
// If the DataTable is already stored in the Web form's default
// HttpSessionState variable, then don't recreate the DataTable.
if (Session["data"] == null)
{
// Add columns to the DataTable.
dt.Columns.Add(new DataColumn("Item"));
dt.Columns.Add(new DataColumn("Price"));
// Store the DataTable in the Session variable so it can
// be accessed again later.
Session["data"] = dt;
// Use the table to create a DataView, because the DataGrid
// can only bind to a data source that implements IEnumerable.
dv = new DataView(dt);
// Set the DataView as the data source, and bind it to the DataGrid.
DataGrid1.DataSource = dv;
DataGrid1.DataBind();
}
}
private void addButton_Click(object sender, System.EventArgs e)
{
// Add the items selected in ListBox1 to DataGrid1.
foreach (ListItem item in ListBox1.Items)
{
if (item.Selected)
{
// Add the item to the DataGrid.
// First, get the DataTable from the Session variable.
dt = (DataTable)Session["data"];
if (dt != null)
{
// Create a new DataRow in the DataTable.
DataRow dr = dt.NewRow();
// Add the item to the new DataRow.
dr["Item"] = item.Text;
// Add the item's value to the DataRow.
dr["Price"] = item.Value;
// Add the DataRow to the DataTable.
dt.Rows.Add(dr);
// Rebind the data to DataGrid1.
dv = new DataView(dt);
DataGrid1.DataSource = dv;
DataGrid1.DataBind();
}
}
}
}
</script>
<html >
<head>
<title> ListItemCollection Example </title>
</head>
<body>
<form id="form1" runat="server">
<h3> ListItemCollection Example </h3>
<table cellpadding="6" border="0">
<tr>
<td valign="top">
<asp:ListBox id="ListBox1" runat="server" SelectionMode="Multiple">
<asp:ListItem Value=".89">apples</asp:ListItem>
<asp:ListItem Value=".49">bananas</asp:ListItem>
<asp:ListItem Value="2.99">cherries</asp:ListItem>
<asp:ListItem Value="1.49">grapes</asp:ListItem>
<asp:ListItem Value="2.00">mangos</asp:ListItem>
<asp:ListItem Value="1.09">oranges</asp:ListItem>
</asp:ListBox>
</td>
<td valign="top">
<asp:Button id="addButton" runat="server" Text="Add -->"
Width="100px" OnClick="addButton_Click"></asp:Button>
</td>
<td valign="top">
<asp:DataGrid Runat="server" ID="DataGrid1" CellPadding="4">
</asp:DataGrid>
</td>
</tr>
</table>
</form>
</body>
</html>

Version Information
.NET FrameworkSupported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

Platforms
Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role not supported), Windows Server 2003 SP2
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Thread Safety
Any public static ( Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also
|
Bibliothèque de classes .NET Framework ListItem, classe Représente un élément de données dans un contrôle de liste lié aux données. Cette classe ne peut pas être héritée.

Hiérarchie d'héritage
Espace de noms :
System.Web.UI.WebControls
Assembly :
System.Web (dans System.Web.dll)

Syntaxe
<TypeConverterAttribute(GetType(ExpandableObjectConverter))> _
Public NotInheritable Class ListItem _
Implements IStateManager, IParserAccessor, IAttributeAccessor
[TypeConverterAttribute(typeof(ExpandableObjectConverter))]
public sealed class ListItem : IStateManager,
IParserAccessor, IAttributeAccessor
[TypeConverterAttribute(typeof(ExpandableObjectConverter))]
public ref class ListItem sealed : IStateManager,
IParserAccessor, IAttributeAccessor
[<Sealed>]
[<TypeConverterAttribute(typeof(ExpandableObjectConverter))>]
type ListItem =
class
interface IStateManager
interface IParserAccessor
interface IAttributeAccessor
end
Le type ListItem expose les membres suivants.

Constructeurs

Implémentations d'interface explicite

Notes
Un contrôle ListItem représente un élément de données individuel dans un contrôle de liste lié aux données, tel qu'un contrôle ListBox ou RadioButtonList. Il y a plusieurs façons de spécifier quel texte sera affiché pour un élément du contrôle de liste. La méthode la plus courante consiste à placer le texte dans le contenu HTML interne. Le contenu HTML interne est le texte situé entre les balises d'ouverture et de fermeture du contrôle ListItem. Vous pouvez également utiliser la propriété Text pour spécifier le texte à afficher dans le contrôle de liste de l'élément. La propriété Value permet d'associer une valeur à un élément du contrôle de liste, outre le texte affiché dans le contrôle. Par exemple, vous pouvez afficher le texte d'un élément du contrôle de liste, tel que "Item 1" puis, avec la propriété Value, spécifier la valeur de cet élément, par exemple "$1.99". La propriété Text ou Value étant définie, toute combinaison du contenu HTML interne est possible. La sortie HTML qui résulte du contrôle ListItem dépend de la combinaison de ces trois propriétés définies. Par exemple, si les trois propriétés sont définies de la manière suivante :
<asp:ListItem Value="Value 1" Text="Item 1">Inner 1</asp:ListItem>
Le contenu HTML interne est utilisé pour le contenu HTML interne rendu et la propriété Value est utilisée pour l'attribut Value. Voici la sortie de rendu HTML :
<option value="Value 1">Inner 1</option>
Le tableau suivant répertorie la combinaison des propriétés définies et de la propriété correspondante, utilisée pour le contenu HTML interne et l'attribut Value. Les trois colonnes de gauche énumèrent les combinaisons de propriétés définies. Les deux colonnes de droite indiquent la valeur utilisée par la propriété pour l'attribut correspondant. Contenu HTML interne | Text, propriété | Value, propriété | Contenu HTML interne rendu | Attribut Value rendu |
|---|
Set | Set | Set | Contenu HTML interne | Value, propriété | Set | Set | Non définie | Contenu HTML interne | Contenu HTML interne | Set | Non définie | Set | Contenu HTML interne | Value, propriété | Set | Non définie | Non définie | Contenu HTML interne | Texte HTML interne | Non définie | Set | Set | Text, propriété | Value, propriété | Non définie | Set | Non définie | Text, propriété | Text, propriété | Non définie | Non définie | Set | Value, propriété | Value, propriété | Non définie | Non définie | Non définie | Non définie | Non définie |
Remarque |
|---|
Étant donné que les propriétés Text et Value ont une chaîne vide comme valeur par défaut, il est possible d'avoir des éléments de liste vides dans le contrôle de liste. |
Lorsqu'un contrôle de liste est affiché, tout contrôle ListItem dont la propriété Selected a la valeur true apparaît en surbrillance dans le contrôle. Le contrôle ListItem fournit la propriété Enabled pour vous permettre de spécifier si un contrôle ListItem est activé ou désactivé. Un contrôle ListItem qui est désactivé est estompé pour indiquer qu'il ne peut pas être sélectionné. Utilisez cette propriété pour désactiver un contrôle ListItem dans un contrôle RadioButtonList ou dans un contrôle CheckBoxList. Remarque |
|---|
Vous ne pouvez pas utiliser cette propriété pour désactiver un contrôle ListItem dans un contrôle DropDownList ou dans un contrôle ListBox. |
Pour obtenir la liste des valeurs de propriétés initiales d'une instance de ListItem, consultez le constructeur ListItem.

Exemples
L'exemple suivant illustre l'utilisation de contrôles ListItem dans un contrôle ListBox. Remarque |
|---|
Les exemples de code suivants utilisent un modèle de code de fichier unique ; il est possible qu'ils ne fonctionnent pas correctement s'ils sont directement copiés dans un fichier code-behind. Chaque exemple de code doit être copié dans un fichier texte vide doté d'une extension .aspx. Pour plus d'informations sur le modèle de code des Web Forms, consultez Modèle de code des pages Web ASP.NET. |
<%@ Page Language="VB" AutoEventWireup="True" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html >
<head>
<title>ListBox Example</title>
<script language="VB" runat="server">
Sub SubmitBtn_Click(Sender As Object, e As EventArgs)
If ListBox1.SelectedIndex > -1 Then
Label1.Text = "You chose: " & ListBox1.SelectedItem.Text
Label1.Text &= "<br /> with value: " & ListBox1.SelectedItem.Value
End If
End Sub
</script>
</head>
<body>
<h3>ListBox Example</h3>
<br />
<form id="form1" runat="server">
<asp:ListBox id="ListBox1" Width="100px" runat="server">
<asp:ListItem>Item 1</asp:ListItem>
<asp:ListItem>Item 2</asp:ListItem>
<asp:ListItem>Item 3</asp:ListItem>
<asp:ListItem Value="Value 4">Item 4</asp:ListItem>
<asp:ListItem Text="Item 5" Value="Value 5" Selected="True"/>
<asp:ListItem>Item 6</asp:ListItem>
</asp:ListBox>
<asp:button Text="Submit" OnClick="SubmitBtn_Click" runat="server" />
<br />
<asp:Label id="Label1" font-names="Verdana" font-size="10pt" runat="server"/>
</form>
</body>
</html>
<%@ Page Language="C#" AutoEventWireup="True" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html >
<head>
<title>ListBox Example</title>
<script language="C#" runat="server">
void SubmitBtn_Click(Object Sender, EventArgs e) {
if (ListBox1.SelectedIndex > -1) {
Label1.Text="You chose: " + ListBox1.SelectedItem.Text;
Label1.Text+="<br /> with value: " + ListBox1.SelectedItem.Value;
}
}
</script>
</head>
<body>
<h3>ListBox Example</h3>
<br />
<form id="form1" runat="server">
<asp:ListBox id="ListBox1" Width="100px" runat="server">
<asp:ListItem>Item 1</asp:ListItem>
<asp:ListItem>Item 2</asp:ListItem>
<asp:ListItem>Item 3</asp:ListItem>
<asp:ListItem Value="Value 4">Item 4</asp:ListItem>
<asp:ListItem Text="Item 5" Value="Value 5" Selected="True"/>
<asp:ListItem>Item 6</asp:ListItem>
</asp:ListBox>
<asp:button Text="Submit" OnClick="SubmitBtn_Click" runat="server" />
<br />
<asp:Label id="Label1" font-names="Verdana" font-size="10pt" runat="server"/>
</form>
</body>
</html>
<!-- This example demonstrates how to select multiple items from a DataList
and add the selected items to a DataGrid. The example uses a For Each loop
to iterate through the ListItem objects in the ListItemCollection of ListBox1. -->
...
<%@ Page language="VB" AutoEventWireup="true"%>
<%@ Import Namespace="System.Data" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
' Global Variables.
Private dv As DataView
Private dt As New DataTable()
Private Sub Page_Load(sender As Object, e As System.EventArgs)
' Set the number of rows displayed in the ListBox to be
' the number of items in the ListBoxCollection.
ListBox1.Rows = ListBox1.Items.Count
' If the DataTable is already stored in the Web form's default
' HttpSessionState variable, then don't recreate the DataTable.
If Session("data") Is Nothing Then
' Add columns to the DataTable.
dt.Columns.Add(New DataColumn("Item"))
dt.Columns.Add(New DataColumn("Price"))
' Store the DataTable in the Session variable so it can be
' accessed again later.
Session("data") = dt
' Use the table to create a DataView, because the DataGrid
' can only bind to a data source that implements IEnumerable.
dv = New DataView(dt)
' Set the DataView as the data source, and bind it to the DataGrid.
DataGrid1.DataSource = dv
DataGrid1.DataBind()
End If
End Sub
Private Sub addButton_Click(sender As Object, e As System.EventArgs)
' Add the items selected in ListBox1 to DataGrid1.
Dim item As ListItem
For Each item In ListBox1.Items
If item.Selected Then
' Add the item to the DataGrid.
' First, get the DataTable from the Session variable.
dt = CType(Session("data"), DataTable)
If Not (dt Is Nothing) Then
' Create a new DataRow in the DataTable.
Dim dr As DataRow
dr = dt.NewRow()
' Add the item to the new DataRow.
dr("Item") = item.Text
' Add the item's value to the DataRow.
dr("Price") = item.Value
' Add the DataRow to the DataTable.
dt.Rows.Add(dr)
' Rebind the data to DataGrid1.
dv = new DataView(dt)
DataGrid1.DataSource = dv
DataGrid1.DataBind()
End If
End If
Next item
End Sub
</script>
<html >
<head>
<title> ListItemCollection Example </title>
</head>
<body>
<form id="form1" runat="server">
<h3> ListItemCollection Example </h3>
<table cellpadding="6" border="0">
<tr>
<td valign="top">
<asp:ListBox id="ListBox1" runat="server" SelectionMode="Multiple">
<asp:ListItem Value=".89">apples</asp:ListItem>
<asp:ListItem Value=".49">bananas</asp:ListItem>
<asp:ListItem Value="2.99">cherries</asp:ListItem>
<asp:ListItem Value="1.49">grapes</asp:ListItem>
<asp:ListItem Value="2.00">mangos</asp:ListItem>
<asp:ListItem Value="1.09">oranges</asp:ListItem>
</asp:ListBox>
</td>
<td valign="top">
<asp:Button id="addButton" runat="server" Text="Add -->"
Width="100px" OnClick="addButton_Click"></asp:Button>
</td>
<td valign="top">
<asp:DataGrid Runat="server" ID="DataGrid1" CellPadding="4">
</asp:DataGrid>
</td>
</tr>
</table>
</form>
</body>
</html>
<!-- This example demonstrates how to select multiple items from a DataList and add the
selected items to a DataGrid. The example uses a foreach loop to iterate through
the ListItem objects in the ListItemCollection of ListBox1. -->
...
<%@ Page language="c#" AutoEventWireup="true"%>
<%@ Import Namespace="System.Data" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script language="C#" runat="server">
// Global Variables.
private DataView dv;
private DataTable dt = new DataTable();
private void Page_Load(object sender, System.EventArgs e)
{
// Set the number of rows displayed in the ListBox to be
// the number of items in the ListBoxCollection.
ListBox1.Rows = ListBox1.Items.Count;
// If the DataTable is already stored in the Web form's default
// HttpSessionState variable, then don't recreate the DataTable.
if (Session["data"] == null)
{
// Add columns to the DataTable.
dt.Columns.Add(new DataColumn("Item"));
dt.Columns.Add(new DataColumn("Price"));
// Store the DataTable in the Session variable so it can
// be accessed again later.
Session["data"] = dt;
// Use the table to create a DataView, because the DataGrid
// can only bind to a data source that implements IEnumerable.
dv = new DataView(dt);
// Set the DataView as the data source, and bind it to the DataGrid.
DataGrid1.DataSource = dv;
DataGrid1.DataBind();
}
}
private void addButton_Click(object sender, System.EventArgs e)
{
// Add the items selected in ListBox1 to DataGrid1.
foreach (ListItem item in ListBox1.Items)
{
if (item.Selected)
{
// Add the item to the DataGrid.
// First, get the DataTable from the Session variable.
dt = (DataTable)Session["data"];
if (dt != null)
{
// Create a new DataRow in the DataTable.
DataRow dr = dt.NewRow();
// Add the item to the new DataRow.
dr["Item"] = item.Text;
// Add the item's value to the DataRow.
dr["Price"] = item.Value;
// Add the DataRow to the DataTable.
dt.Rows.Add(dr);
// Rebind the data to DataGrid1.
dv = new DataView(dt);
DataGrid1.DataSource = dv;
DataGrid1.DataBind();
}
}
}
}
</script>
<html >
<head>
<title> ListItemCollection Example </title>
</head>
<body>
<form id="form1" runat="server">
<h3> ListItemCollection Example </h3>
<table cellpadding="6" border="0">
<tr>
<td valign="top">
<asp:ListBox id="ListBox1" runat="server" SelectionMode="Multiple">
<asp:ListItem Value=".89">apples</asp:ListItem>
<asp:ListItem Value=".49">bananas</asp:ListItem>
<asp:ListItem Value="2.99">cherries</asp:ListItem>
<asp:ListItem Value="1.49">grapes</asp:ListItem>
<asp:ListItem Value="2.00">mangos</asp:ListItem>
<asp:ListItem Value="1.09">oranges</asp:ListItem>
</asp:ListBox>
</td>
<td valign="top">
<asp:Button id="addButton" runat="server" Text="Add -->"
Width="100px" OnClick="addButton_Click"></asp:Button>
</td>
<td valign="top">
<asp:DataGrid Runat="server" ID="DataGrid1" CellPadding="4">
</asp:DataGrid>
</td>
</tr>
</table>
</form>
</body>
</html>

Informations de version
.NET FrameworkPris en charge dans : 4, 3.5, 3.0, 2.0, 1.1, 1.0

Plateformes
Windows 7, Windows Vista SP1 ou ultérieur, Windows XP SP3, Windows XP SP2 Édition x64, Windows Server 2008 (installation minimale non prise en charge), Windows Server 2008 R2 (installation minimale prise en charge avec SP1 ou version ultérieure), Windows Server 2003 SP2
Le .NET Framework ne prend pas en charge toutes les versions de chaque plateforme. Pour obtenir la liste des versions prises en charge, consultez Configuration requise du .NET Framework.

Sécurité des threads
Tous les membres static ( Shared en Visual Basic) publics de ce type sont thread-safe. Il n'est pas garanti que les membres d'instance soient thread-safe.

Voir aussi
RéférenceAutres ressources
|