在ASP.NET WebForm中的PostBack之后关注RadioButtonList中的ListItem

时间:2017-04-05 08:21:17

标签: c# asp.net webforms radiobuttonlist

我想专注于同一个ListItem,它导致asp.net radiobuttonlist中的回发。但目前开发的实现仅关注第一个listitem。有没有办法专注于导致回发的特定列表项。在我的情况下,我不能使用更新面板。我的HTML和CodeBehind如下:

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>

代码隐藏

    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();
    }

1 个答案:

答案 0 :(得分:1)

有几种方法可以做到这一点。您可以从客户端控制整个事物,也可以从服务器端执行此操作:

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);
}