如何将DataGridView绑定到自定义类列表 [英] How to bind a DataGridView to a list of custom classes
问题描述
我有一个使用 TableAdapter
构建的自定义类的列表。
I have a list of custom classes that I am building using a TableAdapter
.
我想添加这些到 DataGridView
仅绑定某些列。
I want to add these to a DataGridView
binding certain columns only.
我尝试了下面的代码来填充和绑定数据:
I have tried the code below to fill and bind the data:
lAllBookings = (From r As DataRow In BookingsTableAdapter1.GetDataWithItems().Rows
Select New Booking With {.bookingID = r.Item("BookingID"), _
.itemID = r.Item("ItemID"), _
.bookedOutDate = r.Field(Of DateTime?)("BookedOutDate"), _
.bookedInDate = r.Field(Of DateTime?)("BookedInDate"), _
.identType = r.Item("IdentType"), _
.identString = r.Item("IdentString"), _
.image = r.Item("Image"), _
.complete = r.Item("Complete"), _
.notes = r.Item("Notes"), _
.itemName = r.Item("ItemName"), _
.itemBC = r.Item("ItemBarcode")}).ToList
dgvBookings.Columns("BookingID").DataPropertyName = "bookingID"
dgvBookings.Columns("ItemIdent").DataPropertyName = "itemName"
dgvBookings.Columns("BookedOut").DataPropertyName = "bookedOutDate"
dgvBookings.Columns("IdentString").DataPropertyName = "identString"
dgvBookings.DataSource = lAllBookings
现在执行此操作时,我得到的行数正确,但是所有字段均为空白。
Now when I do this I get the correct number of rows but all fields are blank.
我已经运行通过一些关于SO的问题和一些教程,但是它们似乎都可以做到ngs与我的需求略有不同。
I've run through a few questions on SO and a few tutorials but they all seem to do things slightly different to what I need.
有没有一种方法可以使用我的项目列表填充 DataGridView
?
如果可以的话,我宁愿避免使用 DataSet
,因为我已经在 List< Of Class>上构建了很多其他代码;
类型。
Is there a way I can fill the DataGridView
using my list of items?
I'd rather avoid using a DataSet
if I can as I've built a lot of other code on this List<Of Class>
type.
编辑-这是Class Booking
声明:
Edit - Here is the Class Booking
declaration:
Public Class Booking
Public bookingID As Integer
Public itemID As Integer
Public itemName As String
Public itemBC As String
Public identType As Short
Public identString As String
Public image As Byte()
Public complete As Boolean
Public notes As String
Public bookedInDate As DateTime?
Public bookedOutDate As DateTime?
End Class
推荐答案
I知道对您来说真的很晚,但也许可以帮助某个人。
I know is really late for you but maybe it can help someone.
我遇到了与您相同的问题,但使用了vb.net。
I had the same problem that you but using vb.net.
最后,我找到了解决方案:您的课程不是在公开属性,而是在公开变量。
Finally I found the solution: Your class was not exposing properties but variables. The binding system looks for properties and can't find them so you get the empty rows.
尝试通过添加 {get; set;}
(如果使用vb.net,则为Property属性),一切都会正常。
Try to complete your class adding {get; set;}
(or the Property attribute if using vb.net) and everything will work.
希望它会有所帮助。
这篇关于如何将DataGridView绑定到自定义类列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!