c# - 使用列表从数据库接收行

标签 c# wpf database xaml database-connection

我正在尝试在数据库连接时填充列表,我已经正确地关闭了 MVVM,但我不知道如何定义列表,然后在该列表中连接到数据库并填充字段。谁能帮忙?我的数据库工作正常...

用户存储库

public class UserRepository: IUserRepository
{

    private System.Data.SqlClient.SqlConnection connectionToDB;

    private System.Data.SqlClient.SqlDataAdapter dataAdapter;

    // Get the data set generated by the sqlStatement
    public System.Data.DataSet getDataSet(string sqlStatement)
    {
        System.Data.DataSet dataSet;

        // creates the object dataAdapter to manipulate a table from the database
        dataAdapter = new System.Data.SqlClient.SqlDataAdapter(sqlStatement, connectionToDB);

        // create the dataset
        dataSet = new System.Data.DataSet();

        dataAdapter.Fill(dataSet);

        //return the dataSet
        return dataSet;
    }
    public List<Users> GetUsers()
    {
        List<Users> users;


        // Database connection to go here along with the list population
        // Something like this?
        //
        // new User
        //     ID = 
        //     FirstName = 
        //     LastName =   

        //  Users = CollectionViewSource.GetDefaultView(_users);



        return users;
    }


}

DBViewModel

public class DBDisplayViewModel
{
    private ObservableCollection<Users> users;

    public DBDisplayViewModel()
    {
        Load();
    }

    public IUserRepository UserRepository
    {
        get; set;
    }

    public ObservableCollection<Users> Users
    {
        get
        {
            if (users == null)
            {
                users = new ObservableCollection<Users>();
            }

            return users;
        }
        set
        {
            if (value != null)
            {
                users = value;
            }
        }
    }

    private void Load()
    {
        List<Users> users= UserRepository.GetUsers();
        Users= new ObservableCollection<Users>(users);
    }
}

用户

这只是定义了 ID FirstName LastName 属性

所以分解一下:需要创建在 UserRepository 中注释掉的信息以拉入数据库连接和数据库值。谁能帮忙?非常喜欢!

最佳答案

看看下面的代码,会给出思路

        public List<Users> GetUsers()
            {
                List<Users> users=new  List<Users> ();
                DataSet ds=getDataSet("Select FirstName,...... from Users")
                Users user;

                 foreach(DataRow row in ds.Tables[0].Rows)
                 {
                   user=new Users();
                   user.FirstName=row["firstname"].ToString();
                    ....
                    ....
                   users.Add(user)
                 }
                return users;
            }

关于c# - 使用列表从数据库接收行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33946017/

相关文章:

c# - 需要用户控件中的接受按钮之类的东西

database - 在 SQL Server 2005 中导出表

wpf - RadChart 样式

c# - 为什么我的按钮在 MouseOver 上没有改变颜色?

mysql - 如何通过比较两个表中的列来填充外键

c# - 需要找到数据库列的类型

c# - 装饰器模式 - 从装饰器访问包装对象中的值

c# - CaSTLe Windsor 注册匹配相同服务的组件

c# - 参数名前面的@有什么作用?

wpf - 在 Windows 8.1 上使用 WindowChrome 时任务栏图标消失