Reputation: 4013
I have this code:
<asp:RadioButtonList ID="rblExpDate" runat="server" >
<asp:ListItem Selected="True" Text="No expiration date"></asp:ListItem>
<asp:ListItem Text="Expires on:"></asp:ListItem>
</asp:RadioButtonList>
that I would like to be always, on page load, to mark the first option ("no expiration date"). However, if the user marks the second option and reloads, the second option is selected, even though I do this on page load:
rblExpDate.Items[0].Selected = true;
rblExpDate.SelectedIndex = 0;
Appreciate your help!
Upvotes: 0
Views: 5207
Reputation: 11
call this function on onload of body tag
<body bottomMargin=0 leftMargin=0 topMargin=25 onload=aa() rightMargin=0>
under the head tag
<script language=Javascript>
function aa() {document.forms[0].item('rblExpDate')[1].disabled=true;}
</script>
Upvotes: 1
Reputation: 11
I had the same problem. I discovered on Page PostBack
that my radioButtonList
was still keeping all previous ListItems selected property
. Basically, the last item of the RadioButtonList
that was previously selected will show up as the item selected on your page. So, in your case, once the user selects the 2nd item, that item has the property checked=checked
despite your code to set the 1st item as selected. Take a look at your View Page Source, you'll see both ListItems being checked.
My solution: on PagePostBack
set the other ListItem Selected propety
value to false like this:
rblExpDate.Items[0].Selected = true;
rblExpDate.Items[1].Selected = false;
This will remove the Checked property on the 2nd item.
Hope that helps someone. Maybe someone has a better way.
Upvotes: 1
Reputation: 4013
The solution I chose is in Javascript (mootools):
window.addEvent('domready', function() {
$("rblExpDate_0").checked = true;
});
(I gave up on the .net side)
thanks for your help @Slavo and @Daniel Dyson.
Upvotes: 0
Reputation: 13230
Are you sure that your code is not within a postback check?
if (!Page.IsPostBack)
{
rblExpDate.Items[0].Selected = true;
rblExpDate.SelectedIndex = 0;
}
More to the point, this sounds like a strange requirement that doesn't sound very useable. Why have an option available if you are always going to override it?
Upvotes: 0
Reputation: 15463
What most probably happens is that the code executed on Page_Load runs first, setting the element you want. After that the SelectedIndexChanged event of the RadioButtonList fires and gets the selected item from the ViewState, overriding what the code did. You have to debug this, though.
Upvotes: 0