ricksmt ricksmt - 1 month ago 13
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>
</asp:RadioButtonList>


I can access the value through
MyControl
, but I can't seem to bind the
SelectedValue
property. The code behind for this page has a public property
InstanceOfMyModel
(backed by Session) of
MyMode
l which has the nullable boolean property
MyProperty
. 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

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