问题添加到Observable Collection

时间:2012-01-27 01:00:21

标签: c# wpf

我在向Observable集合添加项目时遇到问题,我在过去几个小时内尝试过一些事情,但仍然没有让它调试。

错误是对象引用未设置为对象的实例。

这是代码。

public class IPermissionData
{
    public UserListViewModel userListViewModel { get; set; }

    public UserListViewModel GetAllUsers()
    {
        List<string> userList = new List<string>();

        string sqlUsers = "select distinct username from DIMS_roles";
        DataTable tempUserTable = new DataTable();
        tempUserTable = Enviroment._database.GetResults(sqlUsers);

        for (int i = 0; i < tempUserTable.Rows.Count; i++)
        {
            if (tempUserTable.Rows[i]["username"].ToString() != null && tempUserTable.Rows[i]["username"].ToString() != "")
                userList.Add(tempUserTable.Rows[i]["username"].ToString());
        }

        foreach (string user in userList) 
        {
            if (user != null)
            {

                List<string> userPerm = new List<string>();
                string tempPermSql = string.Format("select role from DIMS_roles where username='{0}'", user);
                DataTable tempPermTable = new DataTable();
                tempPermTable = Enviroment._database.GetResults(tempPermSql);

                for (int i = 0; i < tempPermTable.Rows.Count; i++)
                {
                    if (tempPermTable.Rows[i]["role"].ToString() != null && tempPermTable.Rows[i]["role"].ToString() != "")
                        userList.Add(tempPermTable.Rows[i]["role"].ToString());
                }
                //UserViewModel userViewModel = new UserViewModel() { Permission = userPerm, PermCount = userPerm.Count(), UserName = user };
                userListViewModel.TheUsers.Add(new UserViewModel() { Permission = userPerm, PermCount = userPerm.Count(), UserName = user });
            }
        }
        return userListViewModel;
    }

    public IPermissionData() 
    {
        userListViewModel = new UserListViewModel(); 
    }
}

1 个答案:

答案 0 :(得分:1)

应该在视图模型类构造函数中实例化用户可观察集合。如果不是,则为null - 这就是您无法向其添加项目的原因。您无法将项目添加到不存在的项目中。 :)