ASP.NET Basics (part 2): Not My Type - Mixing It Up
(Page 9 of 10 )
Thus far, I have only converted one numeric data type to another. How about converting a string to a number?
C# comes with an entire range of functions to convert a string to any other data type - here's a quick example that demonstrates:
<script language="c#" runat="server">
void Page_Load()
{
// string to convert to number type
string str= "123";
// convert to a int integer
int varInt = Convert.ToInt32(str);
// set the labels
strnumber.Text = str;
intInt.Text = varInt.ToString();
}
</script>
<html>
<head><title>Strings At Play</title></head>
<body>
The string "<asp:label id="strnumber" runat="server" />"... converted to a "int" <asp:label id="intInt" runat="server" />.
</body> </html>
And the output in the browser:

This isn't all - you can also convert a string to any other number type, using the following functions:
Convert.ToSByte(str) - convert str to a sbyte integer
Convert.ToInt16(str) - convert to a short integer variable
Convert.ToInt32(str) - convert to a regular integer variable
Convert.ToInt64(str) - convert to a long integer variable
Convert.ToByte(str) - convert to a byte integer variable
Convert.ToUInt16(str) - convert to an unsigned short integer variable
Convert.ToUInt32(str) - convert to a unsigned integer variable
Convert.ToUInt64(str) - convert to a unsigned long integer variable
What if the string can't be converted to a number, as in the following example?
<script language="c#" runat="server">
void Page_Load()
{
// string to convert to number type
string str= "abc";
// convert to a int integer
int varInt = Convert.ToInt32(str);
// set the labels
strnumber.Text = str;
intInt.Text = varInt.ToString();
}
</script>
<html>
<head><title>Strings At Play</title></head>
<body>
The string "<asp:label id="strnumber" runat="server" />"... converted to a "int" <asp:label id="intInt" runat="server" />.
</body> </html>
What will C# do?

You can also do the reverse - convert a number into a string - by means of the ToString() function, demonstrated below:
<%
// snip
// Set the labels
strnumber.Text = str;
intInt.Text = varInt.ToString();
// snip
%>
Cool, huh?
Next: It's A Wrap >>
More ASP.NET Code Articles
More By Harish Kamath (c) Melonfire