拖一个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>
打开后置cs文件:
写一个GetEmp()方法
/// <summary>
/// 绑定数据库表,指定文本属性和值属性
/// </summary>
/// <returns></returns>
protected DataTable GetEmp()
{
SqlConnection conn = new SqlConnection("server=.;database=northwind;uid=sa;pwd=sa2005");
conn.Open();
SqlCommand cmd = new SqlCommand("select * from employees",conn);
SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
DataTable dt = new DataTable();
dt.Load(dr);
dr.Close();
return dt;
}
protected void BingdingDrop()
{
this.ddlGetId.DataSource = this.GetEmp();
this.ddlGetId.DataTextField = "LastName";
this.ddlGetId.DataValueField = "EmployeeID";
this.ddlGetId.DataBind();
}
在page_load中调用
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
//数据库
BingdingDrop();
}
}
在SelectedIndexChanged事件中声明一个变量用来查看选中值的Id,在声明变量并赋值的这条代码加上断点,按F10调试
protected void ddlGetId_SelectedIndexChanged(object sender, EventArgs e)
{
//string s = this.ddlGetId.DataValueField.ToString();
int i = this.ddlGetId.SelectedIndex;
}
选择第二项的结果如图: