unable to cast the object of type 'System.Data.DataRowView' to type System.IConvertible
In my c# winforms, I am binding Data to DropDownList from a DataTable. The data is visible in the form, but I am not able to get the SelectedValue of this DropDownList.
If I access the SelectedValue then it shows this error:
unable to cast the object of type 'System.Data.DataRowView' to type System.IConvertible.
and the application closes.
There are two or three other DropDownList bound in the same way and they are all are working f开发者_如何学Goine.
The code for the DropDownList is:
LstDriverName.DisplayMember = "DriverName";
LstDriverName.ValueMember = "Driverid";
DriverDetail Driverdetails = new DriverDetail(Constr);
LstDriverName.DataSource = Driverdetails.SelectAllNames();
Here Driverdetails.SelectAllNames() returns a DataTable.
If I check the value in the immediate window:
?LstDriverName.SelectedValue.ToString()
"System.Data.DataRowView"
and the place where the message shows is:
NewBill = new TransportationBill(Constr);
NewBill.DriverId = Convert.ToInt32(LstDriver.SelectedValue);
You can try to do this:
NewBill = new TransportationBill(Constr);
NewBill.DriverId = Convert.ToInt32(LstDriver.SelectedValue.Item["Driverid"]);
Still, it is very strange that you are getting items of type System.Data.DataRowView
Since you have bound to a DataTable, the individual items are of type DataRowView
. These are very similar to a DataRow
: they have columns which contain your data.
It makes no sense for you to try to convert an entire row of data to an integer. What you probably want is something more like this:
var selectedRow = (DataRowView) LstDriver.SelectedValue;
NewBill.DriverId = Convert.ToInt32(selectedRow["Driverid"]);
You want to convert the "Driverid" column of the selected row, not the entire row.
In fact, if the "Driverid" column is already an integer, then you don't need to convert it. Instead:
NewBill.DriverId = (int) selectedRow["Driverid"];
精彩评论