我正在尝试将类列表绑定到WinForms应用程序上的DataGridView。当前,绑定代码不执行任何操作。我已经调试通过,并且源代码正确,其中包含带有正确项目的列表。但我在DataGridView中看不到行。
如何将列表中的内容显示到DataGridView上?此外,当前每次单击“保存”都会清除我的类对象,但是我想保留之前在构造函数中输入的值。如果已经存在一个国家/地区,我希望用户弹出框指出他们是否要重写此文字-这有可能吗/如何才能最好地做到这一点?
CountryWithDates.cs
class CountryWithDates
{
public string country;
public DateTime firstDate;
public DateTime furtherDate;
public DateTime rolldownDate;
public DateTime endDate;
}
在保存时单击:
private void Save_Click(object sender, EventArgs e)
{
List<CountryWithDates> countryDates = new List<CountryWithDates>();
for (int i = 0; i < Countries_LB.Items.Count; i++)
{
if (Countries_LB.GetItemChecked(i))
{
countryDates.Add(new CountryWithDates(){country = Countries_LB.Items[i].ToString(),
firstMarkdownDate = DateTime.Parse(firstDatePicker.Text),
furtherMarkdownDate = DateTime.Parse(furtherDatePicker.Text),
rolldownMarkdownDate = DateTime.Parse(rolldownDatePicker.Text),
endMarkdownDate = DateTime.Parse(endMarkdownPicker.Text)});
}
}
//THIS DOESNT DO ANYTHING - I WANT TO BIND THE SOURCE TO THE GRIDVIEW but i dont see the output in the data gridview on the form when i click save
var bindingList = new BindingList<CountryWithDates>(countryDates);
var source = new BindingSource(bindingList, null);
gv_Countries.DataSource = source;
}
您应该在课堂上创建公共Porperties,而不是公共Fields >>:
class CountryWithDates { //Following the naming rule is good. I'll leave it to you. public string country { get; set; } public DateTime firstDate { get; set; } public DateTime furtherDate { get; set; } public DateTime rolldownDate { get; set; } public DateTime endDate { get; set; } public CountryWithDates() { } public override string ToString() { return country; } }
通过这种方式,您可以将
CountryWithDates
对象的列表绑定到CheckedListBox
:
var lst = new List<CountryWithDates>(); //Add new objects ... //lst.Add(new CountryWithDates { country = "Country 1", firstDate ... }); checkedListBox1.DataSource = null; checkedListBox1.DataSource = lst;
要从列表中获取并更新选中的项目,创建一个新的
BindingSource
,并将其绑定到DataGridView
,您只需执行以下操作:
checkedListBox1.CheckedItems
.Cast<CountryWithDates>()
.ToList()
.ForEach(item =>
{
item.firstDate = firstDatePicker.Value;
item.furtherDate = furtherDatePicker.Value;
item.rolldownDate = rolldownDatePicker.Value;
item.endDate = endMarkdownPicker.Value;
});
dataGridView1.DataSource = null;
var bs = new BindingSource(checkedListBox1.CheckedItems.Cast<CountryWithDates>(), null);
dataGridView1.DataSource = bs;
如果我这样做,我会: