我不明白为什么我的列表不会出现在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();
}
}
}
答案 0 :(得分: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中的演员再次声明,未加载,因此有点空白。
答案 1 :(得分: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" },
};