ListBox





5.00/5 (1投票)
ListBox 控件用于创建列表控件,该控件允许单项或多项选择。使用 Rows 属性指定列表框的高度。
ListBox 控件用于创建列表控件,该控件允许单项或多项选择。使用 Rows 属性指定控件的高度。默认情况下,ListBox 一次只允许进行单项选择。要启用多项选择,请将 SelectionMode 属性设置为“Multiple”。
要指定要在 ListBox 控件中显示的项,请在 ListBox 控件的开始和结束标记之间为每个条目放置一个 ListItem 元素。
<asp:ListBox ID="ListBox1" runat="server">
<asp:ListItem Value="">请选择一项</asp:ListItem>
<asp:ListItem Value="1">项 1</asp:ListItem>
<asp:ListItem Value="2">项 2</asp:ListItem>
</asp:ListBox>
ListBox 控件还支持数据绑定。要将控件绑定到数据源,首先创建一个数据源,例如 DataSourceControl 对象之一,其中包含要在控件中显示的项。然后,使用 DataBind 方法将数据源绑定到 ListBox 控件。使用 DataTextField 和 DataValueField 属性分别指定数据源中要绑定到控件中每个列表项的 Text 和 Value 属性的字段。ListBox 控件现在将显示数据源中的信息。
默认情况下,当控件进行数据绑定时,items 集合中当前存在的任何 ListItem 都将被删除。有时我们可能希望添加一个带有“请选择一项”文本的单个“空”项。为了确保在数据绑定过程中不会删除此项,我们可以将 AppendDataboundItems 属性设置为“true”。
<asp:ListBox ID="ListBox2" runat="server" AppendDataBoundItems="true">
<asp:ListItem Value="">请选择一项</asp:ListItem>
</asp:ListBox>
如果 SelectionMode 属性设置为 Multiple,您可以通过迭代 Items 集合并测试集合中每个项的 Selected 属性来确定 ListBox 控件中选定的项。如果 SelectionMode 属性设置为 Single,您可以使用 SelectedIndex 属性来确定选定项的索引。然后可以使用该索引从 Items 集合中检索该项。
VB
'测试多项选择
Dim selectionList As New System.Collections.Generic.List(Of String)
For Each itm As ListItem In ListBox1.Items
If itm.Selected = True Then
selectionList.Add(itm.Value)
End If
下一篇
'获取单选值
Dim selectionValue As String
selectionValue = Me.ListBox1.SelectedValue
'或
Dim selectedItem As ListItem
selectedItem = Me.ListBox1.SelectedItem
C#
//测试多项选择
System.Collections.Generic.List<string> selectionList = new System.Collections.Generic.List<string>();
foreach (ListItem itm in ListBox1.Items)
{
if (itm.Selected == true)
{
selectionList.Add(itm.Value);
}
}
//获取单选值
string selectionValue;
selectionValue = this.ListBox1.SelectedValue;
//或
ListItem selectedItem;
selectedItem = this.ListBox1.SelectedItem;