I have a Databound Checkbox List and want the selected checkbox item to move to the top of the list.
I've tried searching but all solutions are using html checkbox instead of asp checkbox list
Here is my code for the Checkbox List
<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>
You can do this in the SelectedIndexChanged
event of the CheckBoxList.
<asp:CheckBoxList ID="CheckBoxList1" runat="server" AutoPostBack="true"
OnSelectedIndexChanged="CheckBoxList1_SelectedIndexChanged"></asp:CheckBoxList>
Code behind
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);
}
This may not work with a DataSourceID
. So if it does not you have to start binding data to the CheckBoxList from code behind: http://www.dotnetfox.com/articles/how-to-bind-data-to-checkboxlist-control-in-Asp-Net-using-C-Sharp-1042.aspx