[英]Error with selected item from the ListBox property (C#)?
for (int counter = 0; counter < countSelected; counter++)
{
string groupName = txt_GroupName.Text;
//Get GroupID from the created group
string GroupIDQueryText = "SELECT GroupID FROM tbl_group WHERE GroupName ";
int groupID = Convert.ToInt32(server.performQuery(GroupIDQueryText, groupName, MySqlDbType.VarChar));
//To get User ID
string firstName = ListBoxMembers.SelectedItems[counter].Value;
}
This isn't returning the selected value, but instead returns the 1st person in the list even if I haven't selected it. 这不是返回选定的值,而是返回列表中的第一个人,即使我没有选择它也是如此。 Where am I going wrong?
我要去哪里错了? System.Web.UI.WebControls does not contain defenition for listboxmembers.selectedItems error
System.Web.UI.WebControls不包含listboxmembers.selectedItems错误的定义
You are using .Items
which is the collection of all items in the ListBox
. 您正在使用
.Items
,它是ListBox
中所有项目的集合。 I think you intend to use .SelectedItems
( documentation on MSDN ). 我认为您打算使用
.SelectedItems
( MSDN上的文档 )。
// When counter = 0, this is the very first item in the listbox
ListBoxMembers.Items[counter].Value;
// When counter = 0, this is the first of the selected items in the listbox
ListBoxMembers.SelectedItems[counter].Value;
EDIT Web ListBox controls are different than WinForms ListBox controls, so knowing that context is very valuable. EDIT Web ListBox控件与WinForms ListBox控件不同,因此了解上下文非常有价值。 Here's an article from MSDN on how to determine the selected items in a multi-selection list control (scroll down to the multi-selection section).
这是MSDN上的一篇文章,内容涉及如何确定多重选择列表控件中的选定项目 (向下滚动至“多重选择”部分)。 The idea is to loop through all
.Items
and check the .Selected
property on each. 这个想法是遍历所有
.Items
并检查每个.Selected
属性。
I think you should use ListBox.SelectedValue("Somval");
我认为您应该使用
ListBox.SelectedValue("Somval");
to set selected Value 设置选定的值
It's quite simple: 很简单:
If you have multiple listbox members, like 如果您有多个列表框成员,例如
# | Name | Selected
0 | a | false
1 | b | false
2 | c | true
3 | d | true
then your for
loop with counter = 0
selects the entry (0,a,false)
and not (2,c,true)
at 然后您的
for
counter = 0
循环选择(0,a,false)
而不是(2,c,true)
string firstName = ListBoxMembers.Items[counter].Value;
You have to map the value of the variable counter
to the counter+1
-th selected item or use SelectedItems
, as mentioned by David. 如David所述,您必须将变量
counter
的值映射到第counter+1
个选定项或使用SelectedItems
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.