[英]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;
}
這不是返回選定的值,而是返回列表中的第一個人,即使我沒有選擇它也是如此。 我要去哪里錯了? System.Web.UI.WebControls不包含listboxmembers.selectedItems錯誤的定義
您正在使用.Items
,它是ListBox
中所有項目的集合。 我認為您打算使用.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控件與WinForms ListBox控件不同,因此了解上下文非常有價值。 這是MSDN上的一篇文章,內容涉及如何確定多重選擇列表控件中的選定項目 (向下滾動至“多重選擇”部分)。 這個想法是遍歷所有.Items
並檢查每個.Selected
屬性。
我認為您應該使用ListBox.SelectedValue("Somval");
設置選定的值
很簡單:
如果您有多個列表框成員,例如
# | Name | Selected
0 | a | false
1 | b | false
2 | c | true
3 | d | true
然后您的for
counter = 0
循環選擇(0,a,false)
而不是(2,c,true)
string firstName = ListBoxMembers.Items[counter].Value;
如David所述,您必須將變量counter
的值映射到第counter+1
個選定項或使用SelectedItems
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.