二级菜单级联

本文介绍了一个使用ASP.NET实现的省份和城市级联下拉菜单的完整示例,包括前台页面设置及后台逻辑处理,展示了如何通过事件响应进行数据加载与更新。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

好久没总结了。先总结下这俩个月,看了点.net后台,看了点C++,但不是很多,这俩天看了点php.总结总结下.net遇到的问题吧。

第一个其实就是一个二级菜单的级联问题。

用一个简单的例子说明一下。

例子是一个省份和城市的级联,数据都从一个数据库的一张表里取。

前台代码:俩个DropDownList控件,这里注意AutoPostBack = ”True“ 做级联菜单前一个菜单一定要选上。

 <asp:DropDownList ID="province" style="width:75px;" runat="server"  AutoPostBack="True" 
                  onselectedindexchanged="province_SelectedIndexChanged">
 </asp:DropDownList>
 <asp:DropDownList ID="city" style="width:75px;" runat="server">
 <asp:ListItem>--城市--</asp:ListItem>
 </asp:DropDownList>

看下后台代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using XIS.Brl;
using XIS.Model;

public partial class ComRegiser : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack == false)
        {
            Province_choose();
        }
    }
    protected void Province_choose()
    {
        province.Items.Clear();
        ListItem item = new ListItem();
        item.Text = "--省份--";
        item.Value = "-1";
        province.Items.Add(item);
        PlaceBr typeBr = new PlaceBr();
        List<Place> listType = new List<Place>();
        listType = typeBr.GetAll();
        for (int i = 0; i < listType.Count; i++)
        {
            if (listType[i].Parentid == 0)
            {
                ListItem oItem = new ListItem();
                oItem.Value = listType[i].PID.ToString();
                oItem.Text = listType[i].cnPlaceName;
                province.Items.Add(oItem);
            }
        }
    }
    protected void province_SelectedIndexChanged(object sender, EventArgs e)
    {
        city.Items.Clear();
        ListItem item = new ListItem();
        //载入城市数据
        item.Text = "--城市--";
        item.Value = "-1";    
        city.Items.Add(item);

        PlaceBr placeBr = new PlaceBr();
        List<Place> listcity = new List<Place>();
        listcity = placeBr.GetAll();
        int TypeID = int.Parse(province.SelectedItem.Value);
 
        for (int i = 0; i < listcity.Count; i++)
        {
            if (listcity[i].Parentid !=0&&TypeID == listcity[i].Parentid)
            {
                ListItem oItem = new ListItem();
                oItem.Value = listcity[i].PID.ToString();
                oItem.Text = listcity[i].cnPlaceName;
                city.Items.Add(oItem);
            }
        }
        
    }

}
最后看一下SQL Server里的数据



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值