【问题标题】:Drop Down Not Loaded properly下拉未正确加载
【发布时间】:2013-02-06 05:27:41
【问题描述】:

尊敬的用户,

我的应用程序中有两个下拉菜单,分别是 ddlCountry 和 ddlState。 我有数据库作为

tlb国家

ID(PK) |国名

tlbState

ID(PK) |国家名称 |州名

在加载页面时,我已将 ddlCountry 下拉列表中的所有项目加载为

sqldataadapter da=new sqldataadapter("select countryName from tlbCountry",con);
dataset ds=new dataset();
da.fill(ds);
for(int i=0;i<ds.tables[0].rows.count;i++)
ddlCountry.items.add(ds.Tables[0].Rows[i][0].toString());

当页面被加载时,它的工作正常。 但, 当发生 ddlCountry 的 Textchange 或选择更改事件时,它会尝试从 tlbStates 表中获取相应状态的值,如下所示。它不工作,我做了如下,

sqldataadapter da=new sqldataadapter("select stateName from tlbState where countryName like '"+ddlCountry.selectedItem.toString()+"'",con);
dataset ds=new dataset();
da.fill(ds);
for(int i=0;i<ds.tables[0].rows.count;i++)
ddlState.items.add(ds.Tables[0].Rows[i][0].toString());

在这种情况下,它不会加载 ddlState 下拉菜单。

当我为 ddlCountry 打开自动回发时,它会再次重新加载 ddlState 中没有值的页面。 可能是什么问题?

注意:- 我使用了 AJAX 更新面板。

【问题讨论】:

  • 尝试在更改 ddlCountry 时使用 ddlCountry.selectedItem.Text
  • 在调试时提取状态查询并直接在 SQL Server 中运行并分享您的发现。
  • @Behroz 在调试时发现它不会进入事件函数 selectedindexchanged 用于 ddlcountry 组合,我尝试在 ddlStates 中加载状态以对应 ddlCountry。我为 ddlCountry 设置了自动回发,然后它也没有工作
  • ahan,在 selectionChange 事件应该触发。现在,验证在您的 ASPX 页面的标记中,您能在下拉 tlbState 的标记中看到事件名称吗?
  • 没有我使用过的 onselectedindexchange 事件

标签: asp.net .net


【解决方案1】:

将您的查询更改为:

"select stateName from tlbState where countryName = '" + ddlCountry.Text + "'"

仅当请求不是 PostBack 时,才在 Page_Load 上填充您的 ddlCountry

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        { 
            //Load Countires
            sqldataadapter da = new sqldataadapter("select countryName from tlbCountry", con);
            dataset ds = new dataset();
            da.fill(ds);
            for (int i = 0; i < ds.tables[0].rows.count; i++)
                ddlCountry.items.add(ds.Tables[0].Rows[i][0].toString());
        }
    }

【讨论】:

  • 我的查询可能有误,但主要问题是,它没有出现在 ddlCountry 的 onselectedindexchanged 事件函数中。所以即使这个查询是写的,程序流程也不会达到这个。
  • 检查您没有在每个Load 上添加国家/地区。这将重置 SelectedItem 并导致事件不被触发。
  • 是的,我正在加载它。
  • 您必须只填充一次列表,否则事件不会触发。请参阅我编辑的答案。
  • 哦,是的……我明白了这个问题
【解决方案2】:

希望对你有所帮助。

if (!IsPostBack)
{ 
  //here bind country drop down on page load event.
}

然后在 ddlCountry 绑定状态下拉列表的选择更改事件上

【讨论】:

    猜你喜欢
    • 2021-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    相关资源
    最近更新 更多