How to get information from DataList's footer on buttonClick

1k views Asked by At

I have an ASP.NET DataList, with a footer defined thus:

<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>

What I'm looking to do, is, on click of btnAdd, get the values from txtNotes and ddlStatusList, but I can't work out how to access the controls, let alone the values.

I can't follow something like this because I won't be able to check if my button has been clicked (as is possible with a checkbox), and even then, I'm not sure if I'll be able to use findControl as demonstrated. (Does a DataList's footer behave differently to an item?)

I can't use the Button's commandName & commandValue attributes because, when databound, the text inputted won't exist and therefore I can't set the CommandValue.

I have tried using a LinkButton rather than a normal .NET Button, but come accross the same issue, whereby I cannot work out how to get the values from the TextBox/DropDownList

2

There are 2 answers

1
Adarsh Shah On BEST ANSWER

Following should work. See I added runat="Server" for txtNotes:

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
Emre On

You can use Control.NamingContainer to access other controls in a row:

    <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;
    }