简体   繁体   中英

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

You are using .Items which is the collection of all items in the ListBox . I think you intend to use .SelectedItems ( documentation on 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. 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). The idea is to loop through all .Items and check the .Selected property on each.

I think you should use 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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM