【问题标题】:Bind one Dropdown based on another Dropdown SelectedValue inside DataList - c#基于DataList中的另一个Dropdown SelectedValue绑定一个Dropdown - c#
【发布时间】:2015-01-21 11:27:34
【问题描述】:

我在DataList 中使用了 3 个DropDownList。因此,每一行包含 3 个DropDownListDataList 还包含 DataKeyField

现在,如果用户从DropDownList1 中选择值,那么我想绑定DropDownList2,如果用户从DropDownList2 中选择值,那么我想绑定DropDownList3。我正在使用SelectedIndexChanged,并且能够获得相关DropDownList 选定值的值。但是,如果用户选择DropDownList2,那么我还需要DropDownList1 的值,还需要尊重DataKeyField 的值。

这个怎么弄???

我的代码示例:

<asp:DataList ID="dlTest" runat="server" OnItemDataBound="dlTest_ItemDataBound"
        DataKeyField="TestId">
<ItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"> </asp:DropDownList>
<asp:DropDownList ID="DropDownList2" runat="server" AutoPostBack="true" OnSelectedIndexChanged="DropDownList2_SelectedIndexChanged"> </asp:DropDownList>
<asp:DropDownList ID="DropDownList3" runat="server" AutoPostBack="true" OnSelectedIndexChanged="DropDownList3_SelectedIndexChanged"> </asp:DropDownList>
</ItemTemplate>
</asp:DataList>

在这里,onSelectedIndexChangedDropDownList3,我能够获得它的 selectedValue,但我还需要尊重行的 selectedValue DropDownList1DropDownList2 以及尊重 DataKeyField 值。

protected void DropDownList3_SelectedIndexChanged(object sender, EventArgs e)
    {
        var DropDownList3 = (DropDownList)sender;

        string DDL3 = ((DropDownList)DropDownList3.NamingContainer.FindControl("DropDownList3")).SelectedValue;
        // Also need selectedValue of DropDownList1 and DropDownList2 and DataKeyField.
    }

【问题讨论】:

  • 如果我没记错的话,代码就在那里。而不是.FindControl("DropDownList3"),只需对“DropDownList1”和“DropDownList2”进行查找控制。

标签: c# asp.net drop-down-menu datalist


【解决方案1】:

我想你快到了。你只需要。使用您的代码:

protected void DropDownList3_SelectedIndexChanged(object sender, EventArgs e)
{

    var DropDownList1 = (DropDownList)sender;
    var DropDownList2 = (DropDownList)sender;
    var DropDownList3 = (DropDownList)sender;

    string DDL1 = ((DropDownList)DropDownList1.NamingContainer.FindControl("DropDownList1")).SelectedValue;
    string DDL2 = ((DropDownList)DropDownList2.NamingContainer.FindControl("DropDownList2")).SelectedValue;
    string DDL3 = ((DropDownList)DropDownList3.NamingContainer.FindControl("DropDownList3")).SelectedValue;
}

无论哪种方式,我都会做一些不同的事情:

    item valueddl1 = DropDownList1.SelectedValue;

等等;这应该可以正常工作,而且更简单一些。

【讨论】:

  • 为同一个对象创建三个变量并将它们命名为实际上在标记中不同的对象是不必要且令人困惑的。我不建议这样做。此外,OP 询问如何获取 DataKeyField 值,因此您也应该将其包含在您的答案中。
猜你喜欢
  • 1970-01-01
  • 2013-05-18
  • 1970-01-01
  • 1970-01-01
  • 2018-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-27
相关资源
最近更新 更多