Bind Multiple Lists to a DataGridView

↘锁芯ラ 提交于 2019-12-23 17:23:14

问题


I have two static lists which are to be bound to a DataGridView along with two button fields. I could only bind one list and a button field. Is it possible to bind more than one list to the DataGridView?

ServiceController objSAVAdminService = new ServiceController("SAVAdminService");
ServiceController objSAVService = new ServiceController("SAVService");
ServiceController objPPVService = new ServiceController("PPVService");
ServiceController objMLLService = new ServiceController("MLLService");

List<string> ServiceName = new List<string>();
List<string> ServiceStatus = new List<string>();

ServiceName.Add(objSAVService.ServiceName.ToString());
ServiceName.Add(objSAVAdminService.ServiceName.ToString());
ServiceName.Add(objPPVService.ServiceName.ToString());
ServiceName.Add(objMLLService.ServiceName.ToString());

ServiceStatus.Add( objSAVService.Status.ToString());
ServiceStatus.Add( objSAVAdminService.Status.ToString());
ServiceStatus.Add( objPPVService.Status.ToString());
ServiceStatus.Add( objMLLService.Status.ToString());

I need to bind these two lists to a DataGridView and also two buttons on each row to start or stop the corresponding service.


回答1:


Out of the box there is no support of a data bound DataGridView and two lists. I can see two main options available to you:

  1. Abandon DataBinding -- You don't need to set a list to the DataGridView DataSource property and rely upon DataBinding to get everything working. Instead you can work in unbound mode and write code to move data back and forwards yourself. Have a look at this simple example on MSDN.

  2. Create a Custom Object -- If you want the convenience of data binding you can create some object that combines the two lists, and then bind to that. If you only want one way data binding (not updating the data in the lists when the DataGridView changes) then you can even do this with one simple LINQ query. Otherwise you can write some sort of custom object that acts as a wrapper over the two lists - if you design it well you should be able to have full two way data binding over your two lists.




回答2:


There is another option, because you are using 2 lists of string, you may do that

List<string> BindList = new List<string>();
BindList.AddRange(ServiceName);
BindList.AddRange(ServiceStatus);
foreach(string item in BindList)
{
Datagridview1.Rows.Add(item.objSAVService,item.objSAVAdminService.....)
}


来源:https://stackoverflow.com/questions/6407428/bind-multiple-lists-to-a-datagridview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!