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

后端 未结 3 1737
余生分开走
余生分开走 2020-12-05 15:39

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

3条回答
  •  有刺的猬
    2020-12-05 16:37

    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
        {
    
        }
    }
    

提交回复
热议问题