Search code examples
c#asp.netwebformsradiobuttonlist

Focus on an ListItem in RadioButtonList after PostBack in ASP.NET WebForm


I want to focus on the same ListItem which causes the postback in a asp.net radiobuttonlist. But the implementation that have developed currently is focusing on first listitem only. Is there a way to focus on the particular listitem which causes the postback. I can not use Update panel in my case. My HTML and CodeBehind is as below:

HTML

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:Label ID="lblName" runat="server" Text="Name" AssociatedControlID="txtName"></asp:Label>
            <asp:TextBox ID="txtName" runat="server" Text="Enter your name"></asp:TextBox>
            <br />
            <br />
            <asp:Label ID="lblPersonType" AssociatedControlID="rdoPersonType" runat="server" Text="Person Type"></asp:Label>
            <br />
            <asp:RadioButtonList ID="rdoPersonType" RepeatLayout="Flow" AutoPostBack="true" runat="server" OnSelectedIndexChanged="rboPersonType_Selected"></asp:RadioButtonList>
        </div>
    </form>
</body>
</html>

CodeBehind

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            rdoPersonType.Items.Add(new ListItem() { Text = "Student", Value = "1", Selected = true });
            rdoPersonType.Items.Add(new ListItem() { Text = "Greencard Holder", Value = "2" });
            rdoPersonType.Items.Add(new ListItem() { Text = "Refugee", Value = "3" });
            rdoPersonType.Items.Add(new ListItem() { Text = "Asylum", Value = "4" });
        }
    }

    protected void rboPersonType_Selected(object sender, EventArgs e)
    {
        rdoPersonType.Focus();
    }

Solution

  • There are several ways to do that. You can either control the entire thing from the client side, or you can do this from the server side:

    protected void rboPersonType_Selected(object sender, EventArgs e)
    {
        ClientScript.RegisterStartupScript(
            typeof(Page),
            "SetFocus",
            string.Format("document.getElementById('{0}_{1}').focus();", rdoPersonType.ClientID, rdoPersonType.SelectedIndex),
            true);
    }