开发者

How do I get the selected values in a list box in asp.net

 foreach (ListItem item in ListBoxMembers.Items)
 {
     if (item.Selected)
     {
         countSelected += 1;
     }

 }   
 for (int counter = 0; counter < countSelected; counter++)
 {
    string开发者_如何学Python firstName = ListBoxMembers.SelectedItems[counter].Value;
 }

This isn't returning the selected value. Where am I going wrong? the error it throws is System.Web.UI.WebControls does not contain defenition for listboxmembers.selectedItems error

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using MySql.Data.MySqlClient;
using MySql.Data;
using System.Web.Security;
using System.Data;
using System.Web.UI.WebControls;

These are the name spaces I am using.

This is what I am trying to do

 for (int counter = 0; counter < countSelected; counter++)
            {

        //To get User ID
            string firstName=ListBoxMembers.SelectedItems[counter].Value;

           // string firstName = ListBoxMembers.Items[counter].Value;
            string GUserIDQueryText = "SELECT UserID FROM tbl_user WHERE FirstName ";
            int userID = Convert.ToInt32(server.performQuery(GUserIDQueryText, firstName, MySqlDbType.VarChar));

            //Insert into tbl_userGroups
            string insertIDText = "INSERT INTO tbl_usergroups 

(tbl_group_GroupID,tbl_user_UserID) VALUES(@tbl_group_GroupID,@tbl_user_UserID)";
...
     }

I want to add all the selected users to the table.

the error it throws is System.Web.UI.WebControls does not contain defenition for listboxmembers.selectedItems Are you missing a directory or assembly directive. Why i am not able to use selectedItems


countSelected  =  ListBoxMembers.Items.Cast<ListItem>().Where(i => i.Selected).Count();

if you are trying to get all selected items, you can do

var selectedNames = ListBoxMembers.Items.Cast<ListItem>()
                                  .Where(i => i.Selected)
                                  .Select(i => i.Value)
                                  .ToList()


 List<string> selectedFirstNames = new List<string>();  
 foreach (ListItem item in ListBoxMembers.Items)
 {
     if (item.Selected)
     {
         selectedFirstNames.Add(item.Value);
     }

 }  

//selectedFirstNames has your list of selected first names 


Are you checking for Postback and NOT rebinding when it's a postback? I bet you're blowing away your selected values because you're rebinding. The code in your foreach loop is right.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜