<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ListBox ID="ListBox1" runat="server" Height="187px" SelectionMode="Multiple" Width="141px"></asp:ListBox>
<asp:LinqDataSource ID="LinqDataSource1" runat="server" ContextTypeName="TestDataContext" EntityTypeName="" TableName="Nation">
</asp:LinqDataSource>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="设置选中" />
</div>
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
TestDataContext context = new TestDataContext();
//用代码绑定数据
ListBox1.DataSource = context.Nation;
//显示哪一个字段
ListBox1.DataTextField = "Name";
ListBox1.DataValueField = "Code";
//绑定
ListBox1.DataBind();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
//取选中项的值 只适用于单选
//Label1.Text = ListBox1.SelectedValue.ToString();
//多选
//清值
Label1.Text = "";
foreach (ListItem item in ListBox1.Items)
{
if (item.Selected)
{
Label1.Text += item.Value;//拼接字符串
}
}
}
//设置哪像被选中
protected void Button2_Click(object sender, EventArgs e)
{
foreach (ListItem item in ListBox1.Items)
{
if (item.Text=="汉族"|| item.Text=="满族")
{
item.Selected = true;
}
}
}
}