Reputation: 1036
is there a way to cast/convert the currently selected Row in a datagridview to a custom Object?
For example, I'm trying to cast the selected row to an object of type Client, however, I am unable to do so using this method.
DataGridViewSelectedRowCollection rows = dgvClient.SelectedRows;
foreach (DataGridViewRow r in rows)
{
DataRow myRow = (r.DataBoundItem as DataRowView).Row;
Client current = (Client)myRow;
}
Upvotes: 1
Views: 2527
Reputation: 19881
No, because DataRow
has no relation to Client
- i.e., Client is not derived from DataRow.
Edit: I stand corrected, you can provide an explicit method of casting as @Anand explains. I would recommend this if the Client
source is inaccessible. Otherwise ...
I had a project in VB.Net that used a List as the data source for a DataGridView. What was interesting is that I was able to cast the selected row to SomeEntity
.
What I recommend is provide a constructor, in this case for Client
, that accepts a DataRow as a parameter. Assign values from the row and be done with it:
Client current = new Client(myRow);
Upvotes: 0
Reputation: 14915
You can also use implicit and explicit operator for eg
class Client
{
public static explicit operator Client(DataRow dr)
{
// code to convert from dr to Client
}
}
Client current = (Client)myRow;
similarly you could overload implicit. With implicit operator you the conversion would take automatically with out casts
Upvotes: 2