Reputation: 25
I am creating a system that is accessing a MySQL database, retrieving items as a dataset table and setting the Items from each row to variables in an object. The issue i am having is that when casting the datarow.ItemArray[x] to an integer i am getting the error: System.InvalidCastException. I have checked the database and the Item in the database is defined as Int(10). I have also checked the datarow via debugging in Visual Studio and the value of the Item i am trying to cast as an integer is 1. I will post my code below but if anyone else has had this issue and may know why it would be greatly appreciated.
foreach (DataRow dr in ds.Tables[0].Rows)
{
Group group = new Group();
group.TagID = (int)dr.ItemArray[0];
group.Name = dr[1].ToString();
group.Parent = parent;
Here is the class group.
class Group
{
private int tagID;
private string name;
private Group parent;
List<Group> children = new List<Group>();
List<Tags> tags = new List<Tags>();
Upvotes: 0
Views: 2782
Reputation: 460108
So it is an UInt32
instead of an Int32
, then cast it to that:
group.TagID = (int)(uint)dr[0];
You can also use the Field
method which i prefer since it also supports nullables:
group.TagID = (int)dr.Field<uint>(0);
A third option(in this case probably the best) is to use System.Convert.ToInt32
:
group.TagID = System.Convert.ToInt32(dr[0]);
Upvotes: 2
Reputation: 6872
You have used INT(10), in MySql this means it has 10 digits. Besies you have mentioned the data type is UInt32.
So the solution is to simply cast it into UInt32, instead of using Integer. Or convert it into an inter by using Convert.ToInt32
See below:
grou.TagID = Convert.ToInt32(dr.ItemArray[0])
Upvotes: 0