基于选定的DropDown值重新绑定回发

时间:2008-12-10 22:58:07

标签: c# asp.net data-binding drop-down-menu postback

问候!

我在FormView中有一个DropDownList,它绑定到XmlDataSources:

<asp:FormView ID="MyFormView" runat="server" DataSourceID="MyXmlDataSource">
    <ItemTemplate>
        <h1><%# XPath("SomeNode")%></h1>
        <asp:Label ID="MyLabel" runat="server" AssociatedControlID="MyDdl" Text='<%# XPath("SomeOtherNode")%>' />
        <asp:DropDownList ID="MyDdl"
                          runat="server"
                          DataSourceID="MyDdlDataSource"
                          DataTextField="name"
                          DataValueField="value"
                          AutoPostBack="true"
                          OnSelectedIndexChanged="MyDdl_SelectedIndexChanged">
        </asp:DropDownList>
    </ItemTemplate>
</asp:FormView>
<asp:XmlDataSource ID="MyXmlDataSource" runat="server" XPath="Root/MainSection" />
<asp:XmlDataSource ID="MyDdlDataSource" runat="server" XPath="Root/MainSection/Areas/*" />

在页面的代码隐藏中,我有以下OnLoad()方法以及下拉列表的选择索引更改时的方法:

protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);

    if (!IsPostBack)
    {
        string xml = GetMyXml(0); // default value
        MyXmlDataSource.Data = xml;
        MyDdlDataSource.Data = xml;
    }
}

protected void MyDdl_SelectedIndexChanged(object sender, EventArgs e)
{
    DropDownList l_MyDdl = FindControl("MyDdl") as DropDownList;
    int myVal;
    if (l_MyDdl != null)
        if (!Int32.TryParse(l_MyDdl.SelectedItem.Value, out myVal))
            myVal = 0;
    string xml = GetMyXml(myVal);
    MyXmlDataSource.Data = xml;
    MyDdlDataSource.Data = xml;
}

当从下拉列表中选择不同的值并调用SelectedIndexChanged时,我无法获取下拉列表的值(FindControl始终返回null),以便使用它来重新绑定数据源。我怎样才能得到这个值?

1 个答案:

答案 0 :(得分:1)

因为你的下拉列表包含在另一个控件中,所以你可能需要一个递归的findcontrol。

http://weblogs.asp.net/palermo4/archive/2007/04/13/recursive-findcontrol-t.aspx