C# 如何获取复选框列表的最后选定索引或值
我使用的是一个复选框列表,其中我必须检查最后选定的项目索引或值。下面是一个示例:C# 如何获取复选框列表的最后选定索引或值,c#,asp.net,C#,Asp.net,我使用的是一个复选框列表,其中我必须检查最后选定的项目索引或值。下面是一个示例: 正如我们在这张图片中看到的,橙色、菠萝、西瓜被选中。当我使用foreach循环获取此选定项时,我希望获取最后一个选定项索引 执行for循环,然后将选中的项放在字符串上。最后一个字符串将为您提供最后一项,然后获取其索引。假设您的项目是复选框中的字符串: string strGetLastItem = string.Empty; foreach (object item in checkedListB
正如我们在这张图片中看到的,橙色、菠萝、西瓜被选中。当我使用foreach循环获取此选定项时,我希望获取最后一个选定项索引 执行for循环,然后将选中的项放在字符串上。最后一个字符串将为您提供最后一项,然后获取其索引。假设您的项目是复选框中的字符串:
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
您可以创建一个列表,以在检查项目时保存该项目的索引。在检查项目时,将索引添加到列表中。最后选中的项目将是列表中的最后一个索引(int)。这将让您知道上次检查的内容
var lastItemCheckedIndex = checkedItemsList.Count() - 1;
您还希望确保在取消选中复选框项时,您编写的逻辑考虑了场景/事件。每次取消选中某个项目时,您都会将其从列表中删除。如果列表上的最后一项被删除,那么您仍然能够确定之前检查的最后一项。因为您没有提供足够的代码,假设您已经有了
selectedchangedIndex
方法
尝试按如下方式更新您选择的ChangedIndex。这将给出复选框列表的最后一个选定值
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;
}
}
}
}
protectedvoid yourcheckboxlistname\u SelectedIndexChanged(对象发送方,事件参数e)
{
字符串值=string.Empty;
string result=Request.Form[“\uu EVENTTARGET”];
string[]checkedBox=result.Split(“$”);
int index=int.Parse(checkedBox[checkedBox.Length-1]);
如果(您的CheckboxListName.Items[index]。选中)
{
value=yourcheckboxlistname.Items[index].value;
}
其他的
{
}
//要获取所选值的列表,您可以像
//这个
int lastSelectedIndex=0;
string lastSelectedValue=string.Empty;
foreach(CheckboxListName.Items中的ListItem ListItem)
{
如果(listitem.Selected)
{
int thisIndex=yourcheckboxlistname.Items.IndexOf(listitem);
如果(上次选择的索引<此索引)
{
lastSelectedIndex=此索引;
lastSelectedValue=listitem.Value;
}
}
}
}
最后一个是指列表中最后一个选中的项目还是最后一个被选中的项目?请尝试使用此帖子中的解决方案:。嗨,Tetsuya,我之前已经通过了此链接并进行了测试,所以发生的情况是一个接一个地检查选中的项目,而不是检查并确认此列表中的最后一个项目。嗨,Willy,根据给定的代码,它正在运行完整的循环,然后在结束该循环后检查索引。但是我的需求在这里只是循环中,我应该编写代码来获取列表中最后选择的项目。所以根据这个代码,每个选中的项目页面都会得到刷新,这是我不想要的。我只想将此逻辑放在foreach循环中。@PrityKumari您可以通过将复选框列表1
放在更新面板中来避免重新加载页面