0

in aspx.cs

 string CatID = string.Empty;
    foreach (ListItem li in ListBox1.Items)
    {
        if (li.Selected == true)
        {
            // get the value of the item in your loop
            CatID += li.Value + ",";
        }
    }

In aspx

 <asp:ListBox ID="ListBox1" runat="server" DataSourceID="SqlDataSource1" SelectionMode="Multiple" 
    DataTextField="Username" DataValueField="Username" Height="175px" 
    Width="167px"></asp:ListBox>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
    ConnectionString="<%$ ConnectionStrings:ProjectConnectionString %>" 
    SelectCommand="SELECT * FROM [login_det] WHERE ([Type] = @Type)">
    <SelectParameters>
        <asp:Parameter DefaultValue="User" Name="Type" Type="String" />
    </SelectParameters>
</asp:SqlDataSource>

A piece of code is shown above which will give the output as abc,bcd,efg,hig, when I select four items in the list box. Now is there any possibilities of retrieving these values individually and store it as a string?.Like`

string a = “abc”;
String b=”bcd”;
String c=”efg”;` etc.

Another conflict occurs is that there may be 100’s of items in the list box.and if I select 90 items I should declare or assign the each items with a string variable,which is meaningless.But is there any other possibility of storing or retrieving individual items from the list box?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Shreyas Achar
  • 1,407
  • 5
  • 36
  • 63
  • 1
    Number and selected items in a listbox are a run-time thing. Variables are a compile time thing. You're taking wrong approach. I would suggest you show us what you want to achieve... – Adriano Repetti Jan 28 '14 at 09:31
  • i want to store individual selected items as string variable. – Shreyas Achar Jan 28 '14 at 09:33
  • Yes you said but you can't (compile-time, run-time). Explain **why** you want to do that not the way you would like to do it. – Adriano Repetti Jan 28 '14 at 09:42
  • In my list box i have list of `users`.So selection of the user should make me to insert some data to the `individual user` profile.Hence i need the individual records. – Shreyas Achar Jan 28 '14 at 09:48

5 Answers5

1

Use a List<string> :

List<string> result = new List<string>();
foreach (ListItem li in ListBox1.Items)
{
    if (li.Selected)
    {
        // get the value of the item in your loop
        result.Add(li.Value);
    }
}
Roy Dictus
  • 32,551
  • 8
  • 60
  • 76
Plue
  • 1,739
  • 1
  • 18
  • 22
1

According to your comment you need list of selected items to do some further processing. You don't show your actual code so I'll use a fictional example:

// Let me suppose you're using EF to store some data
using (var context = new DatabaseContext())
{
    foreach (var li in ListBox1.Items.Cast<ListItem>().Where(x => x.Selected))
    {
        // I assume you have user ID (as it's name) in the Value property
        // of each ListItem in your ListBox
        string userName = li.Value;

        var user = context.Users.FirstOrDefault(x => x.Name == userName);

        // This is not redundant, user may even be deleted in another session
        if (user != null)
        {
            // Do changes you need
            user.HasBeenSelected = true;
        }
    }

    // We're done, apply changes you made
    context.SaveChanges();
}

As you see you do not need to create a separate variable for each selected item, you have list of them then you do not need to create another temporary list, just consume selected items doing processing you have to do.

Sorry I can't be more specific without some code to inspect, just another example to make intent clear:

foreach (var li in ListBox1.Items.Cast<ListItem>().Where(x => x.Selected))
{
    var user = Membership.GetUser(li.Value);
    if (user != null)
    {
        user.IsLockedOut = false;
        Membership.UpdateUser(user);
    }
}

From your example (illustration purposes only!):

using (var connection = new SqlConnection(ProjectConnectionString))
{
    connection.Open();

    foreach (var li in ListBox1.Items.Cast<ListItem>().Where(x => x.Selected))
    {
        using (var command = connection.CreateCommand())
        {
            command.CommantText =
                "UPDATE [Login_det] SET Enabled = 0 WHERE Name = @UserName";

            command.Parameters.AddWithValue("UserName", li.Value);
            command.ExecuteNonQuery();
        }
    }
}

Please note that if you have a list of items you may not need to execute multiple commands, you may use a single command with a table parameter. See this post here on SO for a good example.

Community
  • 1
  • 1
Adriano Repetti
  • 65,416
  • 20
  • 137
  • 208
  • 1
    @ShreyasTg added another example, I still don't know what you have to do (not just where data comes from) but it may be similar to what you're doing (just adapt SQL code...it's just an example, I wouldn't hard-code sql code in that way) – Adriano Repetti Jan 28 '14 at 11:05
0
string CatID = string.Empty;
int i = ListBox1.Items.Count(); //not sure with this
string[] CatValues = new string[i];
int iCount = 0;
foreach (ListItem li in ListBox1.Items)
{
    if (li.Selected == true)
    {
        // get the value of the item in your loop
        CatID += li.Value + ",";
        CatValues[iCount] = li.Value;
        iCount++;
    }
}

Then you can loop the CatValues to get all values. I don't know if this will help you

bluejaded
  • 71
  • 6
0

You can use Linq to extract all the selected values and add them to a list, like so:

var selectedValues = from ListItem item in ListBox1.Items where item.Selected select item.Value;
var selectedStrings = selectedValues.ToList();
Matthew Watson
  • 104,400
  • 10
  • 158
  • 276
0

You can use a collection, e.g. List<String> to store the values; Linq could be very convenient to feed the collection

  List<String> result = ListBox1.Items.Cast<ListItem>().Where(x => x.Selected).Select(x => x.Value).ToList();

It's also very easy with Linq to create a comma separated string as you've done:

  string CatID = String.Join(",", ListBox1.Items.Cast<ListItem>().Where(x => x.Selected).Select(x => x.Value));
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215