【问题标题】:How to get information from DataList's footer on buttonClick如何从按钮单击上的 DataList 页脚获取信息
【发布时间】:2023-03-04 17:28:02
【问题描述】:

我有一个 ASP.NET DataList,其页脚是这样定义的:

<FooterTemplate>
    <asp:DropDownList ID="ddlStatusList" runat="server">
    </asp:DropDownList>
    <input id="txtNotes" type="text" placeholder="Notes" />
    <asp:Button runat="server" type="button" Text="Add" ID="btnAdd"></asp:Button>
</FooterTemplate>

我想做的是,单击btnAdd,从txtNotesddlStatusList 获取值,但我不知道如何访问控件,更不用说值了。

我无法关注this 之类的内容,因为我无法检查我的按钮是否已被点击(可以通过复选框来实现),即便如此,我也不确定我是否会能够使用findControl,如图所示。 (DataList 的页脚与项目的行为是否不同?)

我无法使用ButtoncommandNamecommandValue 属性,因为在数据绑定时,输入的文本将不存在,因此我无法设置CommandValue

我尝试使用 LinkButton 而不是普通的 .NET Button,但遇到了同样的问题,因此我无法弄清楚如何从 TextBox/DropDownList 获取值

【问题讨论】:

    标签: c# asp.net datalist findcontrol


    【解决方案1】:

    以下应该可以工作。请参阅我为 txtNotes 添加了 runat="Server":

    aspx:

    <FooterTemplate>
        <asp:DropDownList ID="ddlStatusList" runat="server">
        </asp:DropDownList>
        <input id="txtNotes" runat="server" type="text" placeholder="Notes" />
        <asp:Button runat="server" type="button" Text="Add" ID="btnAdd"></asp:Button>
     </FooterTemplate>
    

    C#:

    protected void btnAdd_Click(object sender, EventArgs e)
        {
            var txtNotes = (System.Web.UI.HtmlControls.HtmlInputText)(((Button)sender).Parent).FindControl("txtNotes");
            var ddlStatusList = (DropDownList)(((Button)sender).Parent).FindControl("ddlStatusList");
        }
    

    【讨论】:

    • +1 - 非常棒!!! DataList 的 DataListItems 在回发时为空。我认为这是最好的方法之一。
    【解决方案2】:

    您可以使用Control.NamingContainer连续访问其他控件:

        <FooterTemplate>
            <asp:DropDownList ID="ddlStatusList" runat="server">
            </asp:DropDownList>
            <input id="txtNotes" type="text" placeholder="Notes" runat="server" />
            <asp:Button runat="server" type="button" Text="Add" ID="btnAdd" OnClick="btnAdd_Click"></asp:Button>
        </FooterTemplate>
    
        protected void btnAdd_Click(object sender, EventArgs e)
        {
            Button btnAdd = (Button)sender;
            DropDownList ddlStatusList = (DropDownList)btnAdd.NamingContainer.FindControl("ddlStatusList");
            System.Web.UI.HtmlControls.HtmlInputText txtNotes = (System.Web.UI.HtmlControls.HtmlInputText)btnAdd.NamingContainer.FindControl("txtNotes");
            int index = ddlStatusList.SelectedIndex;
            string text = txtNotes.Value;
        }
    

    【讨论】:

    • 不幸的是,命名容器 (DataListItem) 在回发时为空。这适用于 GridView,但不适用于 DataList。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-25
    • 1970-01-01
    • 2014-08-08
    • 2021-12-08
    • 2015-10-18
    • 2011-04-24
    相关资源
    最近更新 更多