拖一个DropDownList到内置aspx中,设置属性AutoPostBack为true,在设计中双击控件
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="ddlGetId" runat="server" AutoPostBack="true"
onselectedindexchanged="ddlGetId_SelectedIndexChanged">
</asp:DropDownList>
</div>
</form>
</body>
新建一个Car类,声明两个变量:
public class Car
{
int id;
string name;
public int Id
{
get { return id; }
}
public string Name
{
get { return name; }
}
public Car(int id, string name)
{
this.id = id;
this.name = name;
}
}
打开后置cs文件:
写一个BingdingArray()方法
/// <summary>
/// 绑定数组和自定义数据源
/// </summary>
protected void BingdingArray()
{
Car[] carArray = new Car[3] { new Car(0, "宝马"), new Car(1, "奔驰"), new Car(2, "法拉利") };
List<Car> listArray = new List<Car>();
listArray.AddRange(carArray);
this.ddlGetId.DataSource = listArray;
//让名字显示
this.ddlGetId.DataTextField = "Name";
//让Id隐藏
this.ddlGetId.DataValueField = "Id";
this.ddlGetId.DataBind();
}
在page_load中调用
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
//数组
BingdingArray();
}
}
在SelectedIndexChanged事件中声明一个变量用来查看选中值的Id,在声明变量并赋值的这条代码加上断点,按F10调试
protected void ddlGetId_SelectedIndexChanged(object sender, EventArgs e)
{
//string s = this.ddlGetId.DataValueField.ToString();
int i = this.ddlGetId.SelectedIndex;
}
选择第二项(奔驰)结果如图: