Convert System.Web.UI.WebControls.Unit to int in c#
15,880
Solution 1
The Unit type has a Value property. This is a double, but you can cast it to an int if you want. The casting may cause a loss of precision, but you are probably aware of that.
To create a Unit just use the constructor that takes an int.
Solution 2
If you mean the Unit class:
The Unit class can represent values only between -32768 and 32767.
But it depends if you want the Pixel or Percentage value.
-
myUnit.Value
will get the value as pointed out. - Use the constructor
public Unit(int value)
to convert back.
If you mean a uint: there's 2 possible obvious ways:
int n = Convert.ToInt32(myUint);
int n = (int)myUint;
Solution 3
For ASP.NET Unit:
unit.IsEmpty ? 0 : Convert.ToInt32(unit.Value);
Solution 4
Use Unit.Value property. It will return double and you can cast it to int
Something like (int)xyz.Value
WEhere xyz is the unit variable
To convert int to unit use new Unit(value)
Author by
kartal
Updated on July 13, 2022Comments
-
kartal almost 2 years
How can I convert from an ASP.NET Unit structure to int in c#? Or reverse?
-
KroaX almost 14 yearsYour code will not work properly in many cases ... You need to use the Convert Object to convert from int to Uint and reverse
-
Bastiaan Linders almost 14 yearsJust keep in mind that there is a big difference between UInt and Int32. When converting them you might end up with a wrong result (if the UInt exceeds 2147483647).
-
KroaX almost 14 yearsThats always the risk when converting different numbers
-
Bastiaan Linders almost 14 yearsNot when converting Int32 to Int64 or short to long etc. ;)