views:

140

answers:

1

I have been working on keeping things object oriented for my project. Currently, I'm using a .DLL which supplies all of the app's classes to the WinForms project acting as the presentation layer.

My .DLL will, for example, return a SortableBindingList(Of T) to code in a form. The SortableBindingList(Of T) comes from here. Let's assume a SortableBindingList(Of Product). Assuming that the .DLL's function Services.Products.GetList() returns a SortableBindingList(Of Product), I can easily do this:

DataGridView1.DataSource = Services.Products.GetList()

Now, the DataGridView is properly populated with my list of Products. Fine. However, there is no .SelectedItem property which gives me back my object which was selected in the DataGridView:

' Doesn't exist!
Dim p As Product = DataGridView1.SelectedItem
' Need to make another DB call by getting the Product ID 
' from the proper Cell of the DataGridView ... yuck!

However, a ComboBox or a ListBox does in fact store and return my Product objects intact:

' Valid!
ComboBox1.DataSource = Services.Products.GetList()
Dim p as Product = ComboBox1.SelectedItem

Another however ... the ComboBox and ListBox do not show all of the fields of the Product object, only the value of the DisplayMember property.

Is there a nice control in VB.NET 2008 that I am just missing, which gives me the object oriented functionality that I want which will actually display an entire object's fields and also return that object back when selected by the user? I'm at a loss as to why there wouldn't be.

+2  A: 

It sounds like you're looking for the DataGridView's SelectedRows property. You should be able to use that for what you're describing.

You use it to get the DataBoundItem then cast that to your original class. Let's say I had a list of Product objects bound, I would use something like:

Dim p As Product = CType(dataGridView1.SelectedRows(0).DataBoundItem, Product)
MessageBox.Show(p.Name & " " & p.Price)

This works if the entire row is selected, otherwise you could get a null reference exception. In that case you could get the RowIndex of the currently selected cell via:

dataGridView1.SelectedCells(0).RowIndex

So all together this now looks like:

If dataGridView1.SelectedCells.Count > 0 Then
    Dim index as Integer = dataGridView1.SelectedCells(0).RowIndex
    Dim p As Product = CType(dataGridView1.SelectedRows(index).DataBoundItem, Product)
    MessageBox.Show(p.Name & " " & p.Price)
End If

EDIT: updated to VB.NET

Ahmad Mageed
No, the .SelectedRows property returns an object of type DataGridViewRow, not the object that was originally bound to the DataGridView.
HardCode
Updated answer. You use it to get to your data bound object then cast it appropriately.
Ahmad Mageed
Ah, okay. It works like a charm. Thanks!
HardCode