Itay
Itay

Reputation: 337

Multi Selecting ListBox Items From Array by Value C#

I want to multiselect items from an array,

For some reason, this code throws me an NullReferenceException:

        int[] players = Playerss.GetAllPlayersIDbyMovieID(movie);
        foreach (int playerID in players)
        {
            PlayersListBox.Items.FindByValue(playerID.ToString()).Selected = true;
        }

When I use this code instead, it works but it only keeps the last option selected:

            int[] players = Playerss.GetAllPlayersIDbyMovieID(movie);
            foreach (int playerID in players)
            {
                PlayersListBox.SelectedValue += playerID.ToString();
            }

ASP .net file:

<asp:ListBox ID="PlayersListBox" runat="server" 
            SelectionMode="Multiple"
                   DataSourceID="PlayersAccessDataSource"
                      DataTextField="Player" 
                      DataValueField="PlayerID"           

            ></asp:ListBox> 

Upvotes: 0

Views: 1044

Answers (1)

BrandorK
BrandorK

Reputation: 191

Playerss.GetAllPlayersIDbyMovieID(movie); 

You are probably getting a null exception request because somewhere in the results of your Playerss.GetAllPlayersIDbyMovieID(movie) method there is an option that is not available in PlayersListBox.Items

This could be resolved by checking for null, before you try to set the value of a property for an object that doesn't exist.

int[] players = Playerss.GetAllPlayersIDbyMovieID(movie);
    foreach (int playerID in players)
    {
        var player = PlayersListBox.Items.FindByValue(playerID.ToString());
        if (player != null) 
        {
            player.Selected = true;
        }
    }

Upvotes: 2

Related Questions