从数据库填充DataGridView

时间:2018-03-12 15:43:12

标签: c# database

我有一个DataGridView,我想从我的数据库填充。我有一个空的DataGridView。这是我的剧本和我尝试的内容:

        private void listUser_Load(object sender, EventArgs e)
    {
        List<User> lesUsers = Passerelle.getUsers();
        dgvUser.DataSource = lesUsers;
    }

我的课程:

class User
{
    private int id { get; set; }
    private int level { get; set; }
    private string name { get; set; }
    private string password { get; set; }
    private string email { get; set; }

    public User(int idP, int levelP, string nameP, string passwordP, string emailP)
    {
        id = idP;
        level = levelP;
        name = nameP;
        password = passwordP;
        email = emailP;
    }
}

我获取数据的方式:

    public static List<User> getUsers()
    {
        MySqlDataReader result = executerSelect("SELECT id, level, name, email, password FROM users");
        List<User> users = new List<User>();
        if(result != null)
        {
            while(result.Read())
            {
                int id = int.Parse(result[0].ToString());
                int level = int.Parse(result[1].ToString());
                string name = result[2].ToString();
                string email = result[3].ToString();
                string password = result[4].ToString();
                users.Add(new User(id, level, name, password, email));
            }

        }
        return (users.ToList());
    }

我已尝试使用绑定源,但我无法使用datagridview进行链接

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

您需要指定 lesUsers ,而不是 getUsers 这是一种方法

 List<User> lesUsers = Passerelle.getUsers();
 dgvUser.DataSource = lesUsers ;

修改

检查你是否有公共属性用于在ClassGridView中显示Class的内容作为列