Subtract (-) 2 Text Labels from each other to get result
Well开发者_JAVA技巧, I've tried it with ToInt, ToString, and I'm out of options. I'm trying to substract 2 Label Texts from each other. (Those contains numbers from RSS)
What I have at the moment:
lblOldID.Text = nodeChannel["oldid"].InnerText;
lblNewID.Text = nodeChannel["newid"].InnerText;
So let's say oldid contains "500" and newid "530".
But for some reason, I can't substract (-) them. What I want:
lblResultID.Text = lblOldID.Text - lblNewID.Text;
Example: Result = 530 - 500
So how is that possible?
You need to convert the text to ints.
//These are the ints we are going to perform the calculation on
Int32 oldID = 0;
Int32 newID = 0;
//TryParse returns a bool if the string was converted to an int successfully
bool first = Int32.TryParse(lblOldID.Text, out oldID);
bool second = Int32.TryParse(lblNewID.Text, out newID);
//Check both were converted successfully and perform the calculation
if(first == true && second == true)
{
lblResultID.Text = (oldID - newID).ToString();
}
else
{
lblResultID.Text = "Could not convert to integers";
}
TryParse
prevents an exception being thrown if the data in the labels cannot be converted to integers. Instead, it returns false
(or true
if the numbers were parsed successfully).
If you want the label text to be, literally, 530 - 500
, concatenate the strings like so:
lblResultID.Text = lblOldID.Text + " - " + lblNewID.Text;
If you want the label text to be the result of subtracting the numbers represented in the labels, convert them to integers first:
int old = Int32.Parse(lblOldID.Text);
int new = Int32.Parse(lblNewID.Text);
lblResultID.Text = (old - new).ToString();
(You'll need some error checking in there if there's the possibility that either value might not convert cleanly to an integer)
Perhaps because you really should parse them:
lblResultID.Text = (int.Parse(lblOldID.Text) - int.Parse(lblNewID.Text)).ToString();
Or in string format:
lblResultID.Text = lblOldID.Text + " - "+ lblNewID.Text;
精彩评论