asp.net DropDownList无刷新ajax二级联动实现详细过程

本例只适合新手制作DropDownList无刷新ajax二级联动效果:

数据库实现,添加两表如图:表1,pingpai,表2,type,具体数据库实现看自己的理解:

asp.net DropDownList无刷新ajax二级联动实现详细过程

页面主要代码:

<asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <asp:UpdatePanel runat="server">
            <ContentTemplate>
                <asp:DropDownList ID="DropDownList1" runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"
                    Width="200" AutoPostBack="True">
                </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();;
    }

亲爱的各位战友:www.xiaomi365.com 小米在线 进取随便浏览,支持下我这个苦逼的程序猿。不容易啊!感谢你们了!!

你可能感兴趣的:(asp.net)