0

我不明白为什么我的列表不会出现在 DataGridView 中。如果我删除 dataGridView1.DataSource =actors.ToList(); 的评论 它运行......但是当我按下button_click时我需要它运行。有什么问题?

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        LoadData();
    }


    public void LoadData()
    {
        List<Actor> actors = new List<Actor>
    {
        new Actor(){ PersonId = 1, ForNavn = "xxxx", EtterNavn = "bbbbb", Adresse = "Hhhhhh", PostNr = 37325, PostSted = "aaaa" },
        new Actor(){ PersonId = 2, ForNavn = "ggggg", EtterNavn = "ddddd", Adresse = "Dssssss", PostNr = 37464, PostSted = "ssfff"  },
    };
        //dataGridView1.DataSource = actors.ToList();
    }


    private void btnSok_Click(object sender, EventArgs e)
    {
        List<Actor> actors = new List<Actor>();

        var query = from actor in actors
                    select actor;

        dataGridView1.DataSource = query.ToList();

    }
}

}

4

2 回答 2

2
public partial class Form1 : Form
{
    private List<Actor> _actors;
    public Form1()
    {
        InitializeComponent();
        LoadData();
    }


    public void LoadData()
    {
        _actors = new List<Actor>
    {
        new Actor(){ PersonId = 1, ForNavn = "xxxx", EtterNavn = "bbbbb", Adresse = "Hhhhhh", PostNr = 37325, PostSted = "aaaa" },
        new Actor(){ PersonId = 2, ForNavn = "ggggg", EtterNavn = "ddddd", Adresse = "Dssssss", PostNr = 37464, PostSted = "ssfff"  },
    };
    }


    private void btnSok_Click(object sender, EventArgs e)
    {

        var query = from actor in _actors
                    select actor;

        dataGridView1.DataSource = query.ToList();

    }
}

btnsOK 中的演员再次声明,未加载,因此有点空白。

于 2012-06-26T21:38:58.397 回答
1

因为您的演员列表在按钮单击事件中为空

改用这个:

 List<Actor> actors = new List<Actor>
    {
        new Actor(){ PersonId = 1, ForNavn = "xxxx", EtterNavn = "bbbbb", Adresse = "Hhhhhh", PostNr = 37325, PostSted = "aaaa" },
        new Actor(){ PersonId = 2, ForNavn = "ggggg", EtterNavn = "ddddd", Adresse = "Dssssss", PostNr = 37464, PostSted = "ssfff"  },
    };
于 2012-06-26T21:34:00.510 回答