protected void Page_Load(object sender, EventArgs e) { if(!IsPostBack) { //初始化数据 List<ClassInfo> list = new List<ClassInfo>(); ClassInfo cls1 = new ClassInfo { ClassId=1,ClassName="S1101"}; ClassInfo cls2 = new ClassInfo { ClassId = 2, ClassName = "S2101" }; ClassInfo cls3 = new ClassInfo { ClassId = 3, ClassName = "S2102" }; ClassInfo cls4 = new ClassInfo { ClassId = 4, ClassName = "S3001" }; list.Add(cls1); list.Add(cls2); list.Add(cls3); list.Add(cls4); //绑定数据源 this.ddlClass.DataSource = list; this.ddlClass.DataTextField = "ClassName"; this.ddlClass.DataValueField = "ClassId"; this.ddlClass.DataBind();//如果不写,会如何? //插入友好提示 this.ddlClass.Items.Insert(0, "请选择班级"); } } protected void ddlClass_SelectedIndexChanged(object sender, EventArgs e) { this.lblMessage.Text = "选择的班级信息 ClassId: "+this.ddlClass.SelectedValue.ToString() + " ClassName: " + this.ddlClass.SelectedItem.ToString(); ; }
页面层
<form id="form1" runat="server"> <div> 班级:<asp:DropDownList ID="ddlClass" runat="server" AutoPostBack="True" onselectedindexchanged="ddlClass_SelectedIndexChanged"> </asp:DropDownList> <br /> <asp:Label ID="lblMessage" runat="server" Text=""></asp:Label> </div> </form>
实体层
public class ClassInfo { public ClassInfo() { } public int ClassId { get; set; } public string ClassName { get; set; } }
后台代码