0

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>();

DataRow.ItemArray

Jonny Webb
  • 25
  • 2
  • 10

3 Answers3

2

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]);
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • I then would need to define my object Group as an unsigned integer. This is a correct answer but i will go with Stephens Parsing of a toString method. – Jonny Webb Nov 13 '15 at 12:01
  • "Try this then int.Parse(dr.ItemArray[0].ToString()); – Stephen Brickner 1 min ago" – Jonny Webb Nov 13 '15 at 12:01
  • 1
    @JonnyWebb: i wouldn't convert my value to a different type(which also includes localization issues) and then via `int.Parse` back to a different type. That's error-prone and inefficient. Why don't you make the `TagID` also an `uint` or change the value in the database to `int`? – Tim Schmelter Nov 13 '15 at 12:03
  • @JonnyWebb: maybe in this case the best method is `System.Convert.ToInt32`. I have edited my answer. – Tim Schmelter Nov 13 '15 at 12:06
1

group.TagID = int.Parse(dr.ItemArray[0].ToString());

Stephen Brickner
  • 2,584
  • 1
  • 11
  • 19
0

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])
Don
  • 6,632
  • 3
  • 26
  • 34