ricksmt ricksmt - 1 year ago 106
ASP.NET (C#) Question

Bind SelectedValue in ASP.NET

I don't know why, but I'm really struggling with this. I want to bind a nullable boolean property to a RadioButtonList:

<asp:RadioButtonList ID="MyControl" runat="server" SelectedValue='<%# Bind("InstanceOfMyModel.MyProperty") %>'>
<asp:ListItem Text="Yes" Value="True"></asp:ListItem>
<asp:ListItem Text="No" Value="False"></asp:ListItem>

I can access the value through
, but I can't seem to bind the
property. The code behind for this page has a public property
(backed by Session) of
l which has the nullable boolean property
. Changing the type to string doesn't do anything. The 'bound' property doesn't change: if it was a string before, it's the same string; if it was null, it's still null.

Can anyone tell me what I'm doing wrong? Is there some suppressed conversion issue? I'm not getting compile or runtime errors.

Answer Source

The SelectedValue property cannot be set declaratively. You need to do this in code behind.

MyControl.SelectedValue = "False";

Or if you really do not want to use code behind you can use JavaScript.

<script type="text/javascript">
    var myControl = "<%= MyControl.ClientID %>";
    var myValue = "<%= InstanceOfMyModel.MyProperty %>";
    if (myValue == "True") {
        document.getElementById(myControl + "_0").checked = true;
    } else {
        document.getElementById(myControl + "_1").checked = true;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download