views:

50

answers:

2

I need a way to display, like you see in some web apps, the current characters/character limit for a Text Control(i.e. 3/500). I usually see this as a label residing directly above or below the Text Control.

How is this 'normally' accomplished? Should I override my Text Control somehow? Do I just manually add labels by every Text Control and 'bind' them to properties of the Text Control? Do I need to create a composite control that has the Text Control & Label Controls together to accomplish what I need?

Any direction or help will be greatly appreciated.

+1  A: 
int maxChars = 100;

Textbox onKeyUp:
remainingChars.Text = Convert.ToString(maxChars - textbox.Text.Length);

Stick it in a function:

getRemainingChars(TextBox tb, Label lbl, int max)
{
lbl.Text = Convert.ToString(max - tb.Text.Length) + "/" + Convert.ToString(max);
}

Hopefully thats of some help

Chief17
I am not sure I understand what you are suggesting. Is `remainingChars` a `Label`? If so, shouldn't it be (maxChars - textbox.text.Length).
Refracted Paladin
Ahh, the function part wasn't there when I commented. So you would suggest manually adding labels by each text control and then using this function? Sounds doable, thanks.
Refracted Paladin
Yeah sorry, I got it the wrong way around. And yeah I think thats what I would do. :o) Oh and yes remainingChars is a label
Chief17
+2  A: 

Attach a handler to TextBox.TextChanged and refresh the label based on TextBox.Text.Length and the maximum size you want to allow. You can also enforce the limit in the same handler by calling TextBox.Text = TextBox.Text.Substring( 0, maxChars );.

chaiguy
Just to clarify, this way I would be creating a label for each text control and an event handler for each text control as well? I just want to make sure I am understanding correctly. Thanks
Refracted Paladin
However, only do that last part if the Length is greater than maxChars or you'll get an exception.
chaiguy
If you want, you can package this in a reusable `UserControl` so you only have to write the functionality once.
chaiguy
@Refracted - you could wrap the TextBox and Label in a UserControl.
ChrisF