Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the latest selected value from a checkbox list?

I am currently facing a problem. How to get the latest selected value from a asp.net checkbox list?

From looping through the Items of a checkbox list, I can get the highest selected index and its value, but it is not expected that the user will select the checkbox sequentially from lower to higher index. So, how to handle that?

Is there any event capturing system that will help me to identify the exact list item which generates the event?

like image 723
Masud Rahman Avatar asked Sep 07 '10 00:09

Masud Rahman


1 Answers

If I understood it right, this is the code I'd use:

protected void CheckBoxList1_SelectedIndexChanged(object sender, EventArgs e)
{
    int lastSelectedIndex = 0;
    string lastSelectedValue = string.Empty;

    foreach (ListItem listitem in CheckBoxList1.Items)
    {
        if (listitem.Selected)
        {
            int thisIndex = CheckBoxList1.Items.IndexOf(listitem);

            if (lastSelectedIndex < thisIndex)
            {
                lastSelectedIndex = thisIndex;
                lastSelectedValue = listitem.Value;
            }
        }
    }
}

Is there any event capturing system that will help me to identify the exact list item which generates the event?

You use the event CheckBoxList1_SelectedIndexChanged of the CheckBoxList. When a CheckBox of the list is clicked this event is called and then you can check whatever condition you want.

Edit:

The following code allows you to get the last checkbox index that the user selected. With this data you can get the last selected value by the user.

protected void CheckBoxList1_SelectedIndexChanged(object sender, EventArgs e)
{
    string value = string.Empty;

    string result = Request.Form["__EVENTTARGET"];

    string[] checkedBox = result.Split('$'); ;

    int index = int.Parse(checkedBox[checkedBox.Length - 1]);

    if (CheckBoxList1.Items[index].Selected)
    {
        value = CheckBoxList1.Items[index].Value;
    }
    else
    {

    }
}
like image 111
Leniel Maccaferri Avatar answered Feb 23 '23 21:02

Leniel Maccaferri