1. The HTML Markup
<div> <asp:ListBox ID="ListBox1" runat="server"></asp:ListBox> <br /> <asp:Button ID="Button1" runat="server" Text="Get Selected Values" OnClick="Button1_Click" /> </div>
2. The button event
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { //填充数据 DataTable dt = new DataTable(); dt.Columns.Add(new DataColumn() { ColumnName = "Id", DataType = typeof(int) }); dt.Columns.Add(new DataColumn() { ColumnName = "Name", DataType = typeof(string) }); dt.Rows.Add(1, "Scott"); dt.Rows.Add(2, "John"); dt.Rows.Add(3, "Tom"); dt.Rows.Add(4, "Ross"); ListBox1.DataValueField = "Id"; ListBox1.DataTextField = "Name"; ListBox1.DataSource = dt; ListBox1.DataBind(); } } protected void Button1_Click(object sender, EventArgs e) { int id = int.Parse(ListBox1.SelectedItem.Value); Response.Write(id); }
时间: 2024-10-22 11:48:12