[英]How to display the contents of a list into a DataGridView in winforms
My problem is very simple. 我的问题很简单。 I am making a Calendar for a school project.
我正在为学校项目制作日历。 I need to add certain properties to a list of objects in order to save an event to the calendar.
我需要将某些属性添加到对象列表中,以便将事件保存到日历中。 I have managed to add things to the list, but I have not found a way to display all the events of the list in Winforms.
我设法将内容添加到列表中,但是我没有找到一种在Winforms中显示列表中所有事件的方法。 My professor suggested I use a DataGridView to display the contents of the list.
我的教授建议我使用DataGridView来显示列表的内容。 Can someone show me how I can Bind the objects in my list to a DataGridView, and whenever I add something to the list it also adds it to the grid?
有人可以告诉我如何将列表中的对象绑定到DataGridView,并且每当我向列表中添加内容时,它也会将其添加到网格中? This would be much appreciated.
这将不胜感激。
Here is what I have so far: 这是我到目前为止的内容:
public static List<Event> events = new List<Event>();
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
public static void addEvent(string eventDate, string eventTitle, string eventInfo)
{
Event Event = new Event();
Event.eventDate = eventDate;
Event.eventDate = eventTitle;
Event.eventInfo = eventInfo;
events.Add(Event);
}
}
class Event
{
public string eventDate { get; set; }
public string eventTitle { get; set; }
public string eventInfo { get; set; }
}
} }
Bind your DataGridView to a BindingList instead. 而是将您的DataGridView绑定到BindingList。
Code: 码:
public static void addEvent(string eventDate, string eventTitle, string eventInfo)
{
Event Event = new Event();
Event.eventDate = eventDate;
Event.eventDate = eventTitle;
Event.eventInfo = eventInfo;
events.Add(Event);
var bindinglist = new BindingList<Event>(events);
var source = new BindingSource(bindingList, null);
grid.DataSource = source;
}
You don't need to do anything special: 您不需要做任何特殊的事情:
Event event= new Event();
event.eventDate = eventDate;
event.eventDate = eventTitle;
event.eventInfo = eventInfo;
events.Add(event);
DataGridView1.DataSource = events;
But verify that your Event class is defined as public class 但请确认您的事件类已定义为公共类
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.