C#: Edit a row of a DataTable that contains an int

Don’t use +=, use “cast and +”

d["Count"] = (int)d["Count"] + 1;

Your life would be a lot easier if you make a strongly typed table:

  • Add a new DataSet file to your project
  • Open it, right click anywhere and choose Add DataTable. Name it
  • Right click, add Column, name it Count, set type to Int32
  • Add Type and Size columns similarly

In code use it like:

foreach (var d in dt)
    if (d.Type.Equals(type))
        d.Count += 1;
        d.Size += f.Length;
        found = true;

See all the “indexed by string name returns object that needs cast” crap is gone; it works like any other class with properties that support Intellisense etc. No more “stringly typed” spaghetti.

You can see all the code that CS wrote to make this magic happen in YourDataset.Designer.cs – it’s still a datatable (inherited) and can be used anywhere a DataTable can, but it’s actually pleasant to work with

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top