psmay
psmay

Reputation: 1021

ASP.NET: Show/hide radio button list items programmatically

I need to know how to do what the following would intuitively do if it worked (imagine useGreek() and useNato() to be states that would be consulted once per load or postback):

<asp:radioButtonList id="rbl" runat="server" autoPostBack="true">
    <asp:listItem value="alpha" text="Alpha" />
    <% if(useGreek()) { %>
        <asp:listItem value="beta" text="Beta" />
        <asp:listItem value="gamma" text="Gamma" />
    <% } else if(useNato()) { %>
        <asp:listItem value="bravo" text="Bravo" />
        <asp:listItem value="charlie" text="Charlie" />
    <% } %>
    <asp:listItem value="delta" text="Delta" />
</asp:radioButtonList>

(It will already be apparent that I'm not usually asked to write for IIS.)

Anyway, ASP.NET doesn't like code interleaved with list items, so this is a no-go. I imagine that there's some C#-based way to handle this somehow, but I've been trying for a few days now with no luck.

Also, just to be clear, I'm seeking a server-side solution here. I'm well-versed with jQuery, but we're trying to keep most of the processing of this particular form off the client.

Thanks, and party on.

Upvotes: 1

Views: 7561

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460168

No C# but i think you understand what i mean:

in codebehind's page_load:

If Not IsPostBack Then
    Me.rbl.Items.Add(New ListItem("Alpha", "alpha"))
    If (useGreek()) Then
        Me.rbl.Items.Add(New ListItem("Beta", "beta"))
        Me.rbl.Items.Add(New ListItem("Gamma", "gamma"))
    ElseIf (useNato()) Then
        Me.rbl.Items.Add(New ListItem("Bravo", "bravo"))
        Me.rbl.Items.Add(New ListItem("Charlie", "charlie"))
    End If
    Me.rbl.Items.Add(New ListItem("Delta", "delta"))
End If

If you have to check on every postback because the state could change fast, you could add an Me.rbl.Items.Clear() to the top and remove the PostBack-check.

EDIT: C#

if (!IsPostBack) {
    this.rbl.Items.Add(new ListItem("Alpha", "alpha"));
    if ((useGreek())) {
        this.rbl.Items.Add(new ListItem("Beta", "beta"));
        this.rbl.Items.Add(new ListItem("Gamma", "gamma"));
    } else if ((useNato())) {
        this.rbl.Items.Add(new ListItem("Bravo", "bravo"));
        this.rbl.Items.Add(new ListItem("Charlie", "charlie"));
    }
    this.rbl.Items.Add(new ListItem("Delta", "delta"));
}

Because i'm not sure if you already know the codebehind model, have a look at following link: MSDN: Codebehind and Compilation in ASP.NET 2.0

Upvotes: 2

Related Questions