简体   繁体   中英

How to set ComboBox DataSource properly?

I'm trying to set List as DataSource for ComboBox. User atributes are saved in .txt file in format: username;password;isAdministrator. Referring to MSDN I did everything right.

List<User> users = new List<User>();
    public ComboBoxForm()
    {
        string path = "data\\usr.txt";
        string[] rows = File.ReadAllLines(path);
        for(int i = 0; i < rows.Length; i++)
        {
            string[] atributes = rows[i].Split(';');
            User u = new User(atributes[0], atributes[1], atributes[2]);
            users.Add(u);
        }
            comboBox1.DataSource = users;

        InitializeComponent();
    }

However everytime I run the app, it crashes with NullReferrenceException. What am I missing?

Call InitializeComponent at the start of the constructor, otherwise comboBox1 will be null . comboBox1 is created inside InitializeComponent :

private void InitializeComponent()
{
    ...
    this.comboBox1 = new System.Windows.Forms.ComboBox();
    ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM