Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
375 views
in Technique[技术] by (71.8m points)

asp.net - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
    {

    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...