Bind Multiple Lists to a DataGridView
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(开发者_StackOverflow 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.
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:
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.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.
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.....)
}
精彩评论