How to bind a DataGridView to a list of custom classes - vb.net

I have a list of custom classes that I am building using a TableAdapter.
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.
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.
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.
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 know is really late for you but maybe it can help someone.
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.
Try to complete your class adding {get; set;} (or the Property attribute if using vb.net) and everything will work.
Hope it can be helpful.

I am not sure that you are getting in IAllBookings all the information you want. In any case, you are not passing it rightly to the dgvBookings. Here you have a couple of small codes to help you to understand how this works better:
dgvBookings.Columns.Clear()
Dim newTable As New DataTable
newTable.Columns.Add("Column1")
newTable.Columns.Add("Column2")
newTable.Columns.Add("Column3")
newTable.Rows.Add("1", "2", "3")
newTable.Rows.Add("1", "2", "3")
newTable.Rows.Add("1", "2", "3")
dgvBookings.DataSource = newTable
The newTable emulates perfectly the DataGridView structure (columns & rows) and thus it can be given as a DataSource directly.
Unlikely the case of a simple List:
dgvBookings.Columns.Clear()
Dim newList = New List(Of String)
newList.Add("1")
newList.Add("2")
newList.Add("3")
dgvBookings.DataSource = newList
You are providing less information than expected (1D vs. the expected 2D) and thus the result is not the one you want. You need to provide more information; for example: instead of relying on DataSource, you might add the rows one by one:
dgvBookings.Columns.Add("Column1", "Column1")
For Each item In newList
dgvBookings.Rows.Add(item)
Next
I hope that this answer will help you to understand better how to deal with DataGridView and with the different data sources.
-- UPDATE
Row by row option applied to your specific case.
For Each item As Booking In lAllBookings
With item
dgvBookings.Rows.Add(.bookingID.ToString(), .itemID.ToString(), .bookedOutDate.ToString(), .identString.ToString())
End With
Next

Related

How to display multiple rows with the same ID

Was hoping for some help on this matter. Title pretty much explains what I'm trying to do.
I'm using MySql Database to read the data off the UserID for the purchases they have made, however I've hit a wall because I'm stuck on how to read multiple rows with the same ID.
For exmaple
1, TestProduct
1, TestProduct2
^^^ As there are more rows populated with the same ID how can I read multiple rows?
This is what I'm currently doing and I'm aware this is not working as it's only taking/finding the first ID result it finds and using that one however, I haven't needed to populate multiple rows. So I'm at a loss
SearchUser_COMMAND.Parameters.Add("#userid", MySqlDbType.VarChar).Value = Lbl_UserID.Text
Dim reader2 As MySqlDataReader
reader2 = SearchUser_COMMAND.ExecuteReader()
If reader2.Read() Then
Lbl_Active.Text = reader2(3)
Lbl_ProductName.Text = reader2(2)
Lbl_ProductExpire.Text = reader2(6)
End If
Any help on this matter would be much appreciated.
Thank very much in advance
You could make a class to hold your data, populate a List of those objects, then use some LINQ to iterate over them.
Private Class Data
Public Property Active As Boolean
Public Property Name As String
Public Property Expire As DateTime
End Class
Dim items As New List(Of Data)
If reader2.HasRows Then
While reader2.Read()
items.Add(New Data() With {.Name = CStr(reader2(2)), .Active = CBool(reader2(3)), .Expire = CDate(reader2(6))})
End While
Lbl_Active.Text = String.Join(Environment.NewLine, items.Select(Function(i) i.Active))
Lbl_ProductName.Text = String.Join(Environment.NewLine, items.Select(Function(i) i.Name))
Lbl_ProductExpire.Text = String.Join(Environment.NewLine, items.Select(Function(i) i.Expire))
End If
' maybe clear labels otherwise
For a reader with three items, this should result in something like this
Lbl_Active:
True
True
True
Lbl_ProductName:
name1
name2
name3
Lbl_ProductExpire:
date1
date2
date3
I took the liberty to assume the data types based on the names. You may have all strings in the database (you shouldn't) but then you should use strings.

Can I concatenate 2 columns in my query when using SELECT in ado.net?

VS2013, vb.net
For this class (only the relevant properties are displayed):
Public Class UserPost
Public Property Title As String
Public Property Topic As String
Public Property Type As ChannelType 'ChannelType is an Enum
End Class
The following query returns a simple list(of string) holding the titles of the UserPosts with Topic = topic:
Dim rtnList As New List(Of String)
rtnList = db.UserPost.Where(Function(x) x.Topic = topic).Select(Function(x) x.Anchor.Title).ToList()
But it would be useful to also report the ChannelType as a prefix to the Title. I could create a more complicated object to receive 2 columns and combine them later, but I wondered if there is a way to concatenate the columns in the query so that the rtnList receives the result of:
ChannelType.tostring() & Title
without having to code that afterword.
Of course there is. You just do pretty much exactly what you said. Instead of returning x.Anchor.Title you return x.Anchor.ChannelType.ToString() & x.Anchor.Title.

List (Of T) as DataGridView.DataSource makes sorting fail

I have read some threads about this "error" but I can't figure out how to solve my problem.
I have a class that looks something like this:
Public Class Person
Public Property Name As String
Public Property PhoneNumber As string
Public Property Age As Integer
Public sub New(ByVal Values As String())
Me.Name = Values(0)
Me.PhoneNumber = Values(1)
Me.Age = Convert.ToInt32(Values(2))
End Sub
End Class
I get my data from a semicolon separated file, and i create a list of Person objects by looping this file and split on semicolon. Like this
Dim PersonsList As New List(Of Person)
For Each line in textfile..........
PersonsList.Add(New Person(line.Split(";")))
Next
When the list is complete, I tell my DataGridView that DataSource is PersonsList.
This works like a charm, but I'm not able to sort the columns.
I found this post amongst many (where the class values are not properties, which mine are) and tried that converting function which did'nt really work in my case. The right amount of rows were created, but all of the columns were blank.
What am I missing?
If you use a datatable as the data source, column sorting is automatically enabled and you can sort the data by any column:
Dim dt As New DataTable
dt.Columns.AddRange(
{
New DataColumn("Name"),
New DataColumn("Phone"),
New DataColumn("Age")
})
For Each s As String In IO.File.ReadAllLines("textfile1.txt")
Dim temprow As DataRow = dt.NewRow
temprow.ItemArray = s.Split(";"c)
dt.Rows.Add(temprow)
Next
DataGridView1.DataSource = dt

Grouping by multiple columns

I am not sure if the title is misleading but I wasn't sure how to summarise this one.
I have a table in an SQL DB where a record exists as below:
I would like to display the measurement values of this item in a gridview as below:
I thought about selecting the target values to a list (and the same for the actual values) as below:
Dim cdc As New InternalCalibrationDataContext
Dim allTargetvalues = (From i In cdc.int_calibration_records
Where i.calibration_no = Request.QueryString(0) And
i.calibration_date = Request.QueryString(1)
Select i.measure1_target, i.measure2_target, i.measure3_target).ToList()
Then joining the lists together in some way although I am unsure of how I could join the lists or even if this is the correct approach to be taking?
Well, let me first say that measure1_target, measure2_target, etc. is almost always indicative of bad database design. These should probably be in another table as the "many" end of a 1-to-many relationship with the table you posted. So to answer one of your questions: No, this is not the correct approach to be taking.
With the structure of your table in its current state, your best option is probably something like this:
Dim cdc As New InternalCalibrationDataContext
Dim allTargetValues As New List(Of Whatever)
For Each targetValue In (From i In cdc.int_calibration_records
Where i.calibration_no = Request.QueryString(0) AndAlso
i.calibration_date = Request.QueryString(1)
Select i)
allTargetValues.Add(New Whatever With {.MeasureNumber = 1,
.Target = targetValue.measure1_target,
.Actual = targetValue.measure1_actual })
allTargetValues.Add(New Whatever With {.MeasureNumber = 2,
.Target = targetValue.measure2_target,
.Actual = targetValue.measure2_actual })
allTargetValues.Add(New Whatever With {.MeasureNumber = 3,
.Target = targetValue.measure3_target,
.Actual = targetValue.measure3_actual })
Next
The Whatever class would look like this:
Public Class Whatever
Public Property MeasureNumber As Integer
Public Property Target As Integer
Public Property Actual As Integer
End Class

Populate an Array of Object Based on DataReader Data

I am not sure how to phrase my question properly but I want to achieve something like this.
I have a class named Products
public class Products
private ID as Integer
private Name as String
Public Property ProductID()
Get
Return ID
End Get
Set(ByVal value)
ID = value
End Set
End Property
In one of my code behind pages, I am retrieving data from an SQL Command and placing the same into a datareader object.
How would I be able to declare the class so that each row in my datareader would actually be an instance of the said class?
Like for example:
Dim myProduct() as New Product
Dim intCnt as Integer
While datareaderData.read()
intCnt += 1
myProduct(intCnt) = new Product
myProduct(intCnt).ID = datareaderData("ID")
myProduct(intCnt).Name = datareaderData("Name")
End While
When I do the same, I am getting an error "Object Reference Not Set to an Instance of an Object.
I am quite stumped on this one. Any tips greatly appreciated. Thanks.
You should use an Arraylist or -better- a generic List(of Product).
Besides i would strongly recommend to set Option Strict On in your project's Compiler Settings.
Dim products As New List(Of Product)
While datareaderData.read()
Dim nextProduct As New Product
nextProduct.ProductID = CType(datareaderData("ID"), System.Int32)
nextProduct.Name = datareaderData("Name").ToString
products.add(nextProduct)
End While