如何将选定的复选框移动到复选框列表的顶部

我有一个“数据绑定”复选框列表,希望将选中的复选框项移到列表顶部。

我尝试搜索,但是所有解决方案都使用html复选框而不是asp复选框列表

这是我的复选框列表代码

<asp:CheckBoxList ID="CheckBoxList1" runat="server" DataSourceID="SqlDataSource2" DataTextField="SBrand" DataValueField="SBrand" AutoPostBack="True" SelectedIndexChanged="gvStock_SelectedIndexChanged" OnSelectedIndexChanged="CheckBoxList_SelectedIndexChanged" OnPageIndexChanging="gvStock_PageIndexChanging" CssClass="checkboxlist">
</asp:CheckBoxList>
hxbaby 回答:如何将选定的复选框移动到复选框列表的顶部

您可以在CheckBoxList的SelectedIndexChanged事件中执行此操作。

<asp:CheckBoxList ID="CheckBoxList1" runat="server" AutoPostBack="true" 
    OnSelectedIndexChanged="CheckBoxList1_SelectedIndexChanged"></asp:CheckBoxList>

后面的代码

protected void CheckBoxList1_SelectedIndexChanged(object sender,EventArgs e)
{
    //get the index of the last changed checkbox
    int index = Convert.ToInt32(Request.Form["__EVENTTARGET"].Split('$').Last());

    //find the correct listitem in the checkboxlist
    ListItem item = CheckBoxList1.Items[index];

    //if the item is already in first position do nothing
    if (index == 0)
        return;

    //remove it from it's current position
    CheckBoxList1.Items.RemoveAt(index);

    //add the listitem at the top
    CheckBoxList1.Items.Insert(0,item);
}

这可能不适用于DataSourceID。因此,如果不是这样,则必须从后面的代码开始将数据绑定到CheckBoxList:http://www.dotnetfox.com/articles/how-to-bind-data-to-checkboxlist-control-in-Asp-Net-using-C-Sharp-1042.aspx

本文链接:https://www.f2er.com/3139460.html

大家都在问