通过值C#从数组中选择ListBox项目

时间:2014-06-05 00:41:25

标签: c# asp.net listbox checkedlistbox

我想多选一个数组中的项目,

由于某种原因,这段代码会抛出一个NullReferenceException:

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

当我使用此代码时,它可以工作,但它只保留最后一个选项:

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

ASP .net文件:

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

            ></asp:ListBox> 

1 个答案:

答案 0 :(得分:2)

Playerss.GetAllPlayersIDbyMovieID(movie); 

您可能会收到一个空的异常请求,因为Playerss.GetAllPlayersIDbyMovieID(movie)方法的结果中有一个选项在PlayersListBox.Items中不可用

在尝试为不存在的对象设置属性值之前,可以通过检查null来解决此问题。

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