如何获取最后选择的checkboxlist的索引或值

时间:2017-04-12 02:42:13

标签: c# asp.net

我正在使用一个复选框列表,我必须检查最后选择的项目索引或值。下面是一个例子:

Image here for your reference

正如我们在这张图片中看到的那样,橙色,菠萝,西瓜被选中。当我以前使用foreach循环获取此选定项目时,我想获得最后选择的项目索引。

3 个答案:

答案 0 :(得分:1)

由于您没有提供足够的代码,假设您已经拥有selectedchangedIndex方法。

尝试更新SelectedChangedIndex,如下所示。这将给出复选框列表的最后选择值

protected void yourcheckboxlistname_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 (yourcheckboxlistname.Items[index].Selected)
    {
        value = yourcheckboxlistname.Items[index].Value;
    }
    else
    {

    }


   // For getting the list of values that are selected u can get it like  
    //this
    int lastSelectedIndex = 0;
  string lastSelectedValue = string.Empty;

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

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

答案 1 :(得分:0)

执行for循环然后将选中的项放在字符串上。最后一个字符串将为您提供最后一项,然后获取其索引。假设您的项目是CheckListBox中的字符串:

string strGetLastItem = string.Empty;

       foreach (object item in checkedListBox1.CheckedItems)
        {
            strGetLastItem = (string)item;
        }

       int index = checkedListBox1.Items.IndexOf(strGetLastItem);

//strGetLastItem will give you the last checked item.
//index will get the index of the item

答案 2 :(得分:0)

您可以创建一个List来保存项目的索引。在检查项目时,将索引添加到列表中。检查的最后一项将是列表中的最后一个索引(int)。这将让您知道最后检查的内容。

var lastItemCheckedIndex = checkedItemsList.Count() - 1;

您还希望确保在取消选中复选框项时,您编写的逻辑会对场景/事件进行说明。每次取消选中某个项目时,都会将其从列表中删除。如果列表中的最后一项被删除,那么您仍然可以确定之前检查过的最后一项。