Coverting string to int and...

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hey
I have very simple problem... I have label let's say it's lbl. So I need it
to display a counter:
int counter = Convert.ToInt32(lbl.Text) +1
bl.Text = counter;

In VB.Net I made it like this :
lbl.Text +=1

is there any way, to make it one line in C# ?
Jarod
 
I would assume that VB.Net lets you get away with that because it performs
all the casting for you. There are a few ways in C#, here's one.

lbl.Text = (Convert.ToInt32(lbl.Text) + 1).ToString();
 
Jarod,

You can make it one line in C#, but it won't be as elegant:

// Increment the text of the label by adding one to the number that is on
the label.
lbl.Text = (++Convert.ToInt32(lbl.Text)).ToString();

The reason that works in VB is because it will perform automatic type
conversion. In reality, VB is converting the text to an integer,
incrementing it by 1, then converting back to a string, and then assigning
it back to the property.

Hope this helps.
 
Sorry, kill that ++, I don't know what I was thinking. Just add +1.

--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)

Nicholas Paldino said:
Jarod,

You can make it one line in C#, but it won't be as elegant:

// Increment the text of the label by adding one to the number that is on
the label.
lbl.Text = (++Convert.ToInt32(lbl.Text)).ToString();

The reason that works in VB is because it will perform automatic type
conversion. In reality, VB is converting the text to an integer,
incrementing it by 1, then converting back to a string, and then assigning
it back to the property.

Hope this helps.


--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)

Jarod said:
Hey
I have very simple problem... I have label let's say it's lbl. So I need
it
to display a counter:
int counter = Convert.ToInt32(lbl.Text) +1
bl.Text = counter;

In VB.Net I made it like this :
lbl.Text +=1

is there any way, to make it one line in C# ?
Jarod
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top