【问题标题】:How to get the last selected index or value of checkboxlist如何获取最后选择的索引或复选框列表的值
【发布时间】:2017-04-12 02:42:12
【问题描述】:

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

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

【问题讨论】:

  • 最后是指列表中最后一个被选中的还是最后被选中的?
  • 尝试使用这篇文章中的解决方案:stackoverflow.com/questions/3655068/…
  • 嗨 Tetsuya,我之前已经浏览过此链接并进行了测试,所以它正在逐一检查所选项目,而不是检查并确认在此列表中选择了最后一个项目。

标签: c# asp.net


【解决方案1】:

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

尝试更新您的 SelectedChangedIndex 如下。这将给出 checkboxlist 的 Last selected 值

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

【讨论】:

  • 您好 Webruster,您知道我正在使用复选框列表。因此,根据此代码,每个检查项目页面都会刷新我不想要的。我只想把这个逻辑放在 foreach 循环中。
  • @PriityKumari 您可以通过将Checkboxlist1 保留在updatepanel 中来避免页面重新加载
【解决方案2】:

执行 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

【讨论】:

  • 嗨,威利,根据给定的代码,它正在运行完整的循环,然后在结束此循环后检查索引。但是我的要求只是在循环中我应该编写代码来获取列表中选择的最后一项。
【解决方案3】:

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

var lastItemCheckedIndex = checkedItemsList.Count() - 1;

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

【讨论】:

    猜你喜欢
    • 2013-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-23
    • 1970-01-01
    • 2011-04-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多