Default.aspx内容`
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>无标题页</title>
</head>
<body>
<form id="form1" runat="server">
<div>
学生列表:<br/>
<asp:ListBox ID="ListBox1" runat="server" Height="200px" Width="200px"
Font-Size="Small" onselectedindexchanged="ListBox1_SelectedIndexChanged"
AutoPostBack="True"></asp:ListBox>
<br />
<asp:Label ID="Label1" runat="server" Text="" ForeColor="Red"></asp:Label>
</div>
</form>
</body>
</html>
向ListBox1控件绑定数据
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DataSet ds = new DataSet();//
ds.Tables.Add("stu");
ds.Tables["stu"].Columns.Add("stuNo", typeof(int));
ds.Tables["stu"].Columns.Add("stuName", typeof(string));
ds.Tables["stu"].Columns.Add("stuScore", typeof(int));
ds.Tables["stu"].Rows.Add(new object[] { 1, "张一", 100 });
ds.Tables["stu"].Rows.Add(new object[] { 2, "王二", 100 });
ds.Tables["stu"].Rows.Add(new object[] { 3, "李三", 100 });
ds.Tables["stu"].Rows.Add(new object[] { 4, "赵四", 100 });
ds.Tables["stu"].Rows.Add(new object[] { 5, "周五", 100 });
this.ListBox1.DataSource = ds.Tables["stu"];
this.ListBox1.DataValueField = "stuNo";
this.ListBox1.DataTextField = "stuName";
this.ListBox1.DataBind();
}
}
事件函数ListBox1_SelectedIndexChanged
protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
this.Label1.Text = "你选择的学生是:学号 " + this.ListBox1.SelectedValue.ToString() + " 姓名 " + this.ListBox1.SelectedItem.Text.ToString();
}
这是运行结果:
这是程序设计图: