資料庫實現,添加兩表表1,pingpai,表2,type,具體資料庫實現看自己的理解:
頁面主要代碼:
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"
Width="200" >
</asp:DropDownList>
<asp:DropDownList ID="DropDownList2" runat="server" Width="200">
</asp:DropDownList>
</ContentTemplate>
</asp:UpdatePanel>
//以上代碼實現ajax的無重新整理效果
程式主要代碼:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindDrop();
}
}
private void BindDrop()
{
//將資料捆綁到下拉式清單中
string sqlStr = "select * from pingpai";
DataTable dt=DataBase.GetTable(sqlStr);
DropDownList1.DataTextField = "pingpai"; //設定列表顯示的字
DropDownList1.DataValueField = "typeid"; //設定列表提交後獲得的欄位,自己理解為隱藏綁定資料
DropDownList1.DataSource = dt.DefaultView;
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, new ListItem("請選擇車子品牌", ""));//第一項中加入內容,重點是綁定後添加
DropDownList2.Items.Insert(0, new ListItem("請選擇車子品牌型號", ""));//第一項中加入內容,重點是綁定後添加
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
int typeid = Convert.ToInt32(DropDownList1.SelectedValue);//頁面載入後DropDownList1.DataValueField隱藏繫結資料,後邊根據它查詢DropDownList2要顯現的資料
string sqlStr = "select * from type where typeid='" + typeid + "'";
DataTable dt = DataBase.GetTable(sqlStr);
DropDownList2.DataTextField = "type"; //設定DropDownList1事件SelectedIndexChanged改變後DropDownList2列表顯示的資料
DropDownList2.DataSource = dt.DefaultView;
DropDownList2.DataBind();;
}