473,587 Members | 2,580 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Is there anything special about '%' or "%"?

Jax
Custom control problem.
I'm modding a textbox so that it will always have a "%"
sign at the end of it.
I have overrided the Text property to account for the "%"
value within the textbox and have add BaseText to give
access to the baseText method too.
I have the text_changed event handler wired up to this
method, problem is that it works ONLY every other time.
The statement that works every other time is this:

string s = ResultOfOtherTh ings();
this.BaseText = s + "%";

In debugger I can see it doesn't add the "%";
I've tried:

s = s+"%";

But in the debugger s appears without the "%".
So therefore I ask is there anything "special" about '%'
or "%" because it's making little sense at best.
Full code follows:

public class PercentBox : System.Windows. Forms.TextBox
{
//Characters that are allowed to be typed into the box
private ArrayList allowedChars;

public ArrayList AllowedChars
{
get{return allowedChars;}
set{allowedChar s = value;}
}
// my override of text
public override string Text
{
get
{
if(base.Text.Le ngth>1)
{
return base.Text.Subst ring(0, base.Text.Lengt h-1);
}
else
{
return "";
}
}
set{base.Text = value + "%";}
}
// to give access to the base still
public string BaseText
{
get{return base.Text;}
set{base.Text = value;}
}
public PercentBox()
{
base.Text = "%";
this.TextChange d += new EventHandler
(PercentBox_Tex tChanged);
this.KeyPress += new
System.Windows. Forms.KeyPressE ventHandler
(PercentBox_Key Press);
allowedChars = new ArrayList(10);
allowedChars.Ad d('0');
allowedChars.Ad d('1');
allowedChars.Ad d('2');
allowedChars.Ad d('3');
allowedChars.Ad d('4');
allowedChars.Ad d('5');
allowedChars.Ad d('6');
allowedChars.Ad d('7');
allowedChars.Ad d('8');
allowedChars.Ad d('9');
allowedChars.Ad d((char)8);
allowedChars.Ad d('.');
allowedChars.Ad d('%');
}

protected override void OnPaint(PaintEv entArgs pe)
{
// TODO: Add custom paint code here

// Calling the base class OnPaint
base.OnPaint(pe );
}
private void PercentBox_Text Changed(object sender,
System.EventArg s e)
{
PercentBox pBox = (PercentBox) sender;
if(pBox.BaseTex t.Length>0)
{
// to make sure there only 1 % mark so the next if
//statement will work
string s = OnlyOneCharOfTy pe(pBox.BaseTex t, '%');
if(s[s.Length-1] != '%')
{
// remove the eventhandler during the operation
this.TextChange d -= new EventHandler
(PercentBox_Tex tChanged);
string victim = pBox.BaseText;
// removes all '%' from victim
s = RemoveCharFromS tring(victim, '%');
// make sure there is only one decimal place
s = OnlyOneCharOfTy pe(s, '.');
pBox.BaseText = s+"%";
this.TextChange d += new EventHandler
(PercentBox_Tex tChanged);
}
}
else
{
pBox.BaseText = "%";
}
}
private string OnlyOneCharOfTy pe(string victim, char type)
{
bool found = false;
char[] result = new char[victim.Length];
int charCtr = 0;
foreach(char c in victim)
{
if(c == type)
{
if(found != true)
{
found = true;
result[charCtr] = c;
charCtr++;
}
else
{
continue;
}
}
else
{
result[charCtr] = c;
charCtr++;
}
}
StringBuilder sb = new StringBuilder() ;
foreach(char ch in result)
{
try
{
sb.Append(ch);
}
catch(Exception )
{
break;
}
}
string theResult = sb.ToString();
theResult = theResult.Trim( );
return theResult;
}
private string RemoveCharFromS tring(string victim, char c)
{
char[] result = new char[victim.Length];
int charCtr = 0;
foreach(char ch in victim)
{
if(ch != c)
{
result[charCtr] = ch;
charCtr++;
}
}
StringBuilder sb = new StringBuilder() ;
foreach(char ch in result)
{
try
{
sb.Append(ch);
}
catch(Exception )
{
break;
}
}
string theResult = sb.ToString();
theResult = theResult.Trim( );
return theResult;
}
/// <summary>
/// // Ensures that no letters can be added to a control
that has the key press event linked to this
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PercentBox_KeyP ress(object sender,
System.Windows. Forms.KeyPressE ventArgs e)
{
char c = e.KeyChar;
if(!ValidatePre ssEntry(c))
{
e.Handled = true;
}
}
/// <summary>
/// // Ensures that no letters can be
added to a control that has the key press event linked to
this save the '.' character for decimal places
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private bool ValidatePressEn try(char c)
{
bool bob = false;
foreach(char okChar in allowedChars)
{
if(okChar == c)
{
bob = true;
}
}
return bob;
}
}
Nov 15 '05 #1
6 1604
Not sure if I understand the problem. The control appears to work as it
should.
% is displayed at the end, no matter what text is entered or assigned to
PercentBox.Text .
% also shows up as expected in the debugger (Visual Studio .Net 2003)

--
Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/
Nov 15 '05 #2
Jax
Thanks for the reply Morten,
I'm runnning Visual Studio 2002 standard addition, I have
implemented an almost identical text box with a "£" infront
for currency values so I dont think there are any problems
in the setting up of the custom control.
The situation that i'm trying to prevent is the ability to
add numbers after the % mark, the code (as i'm sure you
understand) should correct this remove the "%" analyze the
remainder and then add the % to the end.
This is an example of me using it:

Percentbox value: %
change to: %5
result: 5
change to: 55
result: 55%
change to: 55%5
result: 555

I'm stepping through the debugger as well and on the line,
pBox.BaseText = s + "%";
the "%" does not get added to BaseText just string s is
added.
What on earth is going on?
Is there another/better/slightyworse way around this?

Thanks for the help.
jax

-----Original Message-----
Not sure if I understand the problem. The control appears to work as it should.
% is displayed at the end, no matter what text is entered or assigned to PercentBox.Tex t.
% also shows up as expected in the debugger (Visual Studio .Net 2003)
--
Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/.

Nov 15 '05 #3
Jax
Fascinating, I fixed it.
pBox.BaseText = s;
pBox.BaseText += "%";

And it's fine.
????
any suggestions as to why this doesn't work on one line?

jax
-----Original Message-----
Thanks for the reply Morten,
I'm runnning Visual Studio 2002 standard addition, I have
implemented an almost identical text box with a "£" infrontfor currency values so I dont think there are any problems in the setting up of the custom control.
The situation that i'm trying to prevent is the ability to add numbers after the % mark, the code (as i'm sure you
understand) should correct this remove the "%" analyze the remainder and then add the % to the end.
This is an example of me using it:

Percentbox value: %
change to: %5
result: 5
change to: 55
result: 55%
change to: 55%5
result: 555

I'm stepping through the debugger as well and on the line,
pBox.BaseTex t = s + "%";
the "%" does not get added to BaseText just string s is
added.
What on earth is going on?
Is there another/better/slightyworse way around this?

Thanks for the help.
jax

-----Original Message-----
Not sure if I understand the problem. The control appears to work as it
should.
% is displayed at the end, no matter what text is

entered or assigned to
PercentBox.Te xt.
% also shows up as expected in the debugger (Visual

Studio .Net 2003)

--
Using M2, Opera's revolutionary e-mail client:

http://www.opera.com/m2/
.

.

Nov 15 '05 #4
Ah, I got it, adding a number after the % will clear the % (entering % by
hand will also clear it!!!)

Well, you could store the "real" textbox as a private string

private string realNumber = "";

public override string Text
{
get
{
return realNumber;
}
set
{
realNumber = value; // make sure this is a valid number without %
base.Text = realNumber + "%";
}
}

Also, in the keypress event, set everything e.Handled = true;
and if validchar add the character to realNumber;
Note: you will have to handle arrow keys and deletion insertion, cursor
position

Or remove the ability to enter % and possibly prevent the user moving past
the % (this would require handling END and arrow keys, but I bet it would
look cool :p

--
Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/
Nov 15 '05 #5
Jax
Well i have got it sorted now by splitting the line

pBox.BaseText = s + "%";

into two lines
pBox.BaseText = s;
pBox.BaseText += "%"

like so.
No idea why that works and the top line didn't, it's gonna
confuse me for ages.

The hnadling I have for the key presses at the moment
allows you to specify in the arraylist allowedChars which
chars to allow through.
(bkspc has to be done in code though: allowedChars.Ad d
((char)8);)
That also allows all arrow keys and delete.
Only problem is that shift+number keys are going through
as well(!"£$%^&*() ), fortunately I have exception handling
when I gather the results so it wont crash it.
And I could easily add some code to make sure shift isn't
being pressed.... i'll do it later.

Thanks for the feedback morten, i really appreciate it.

jax
-----Original Message-----
Ah, I got it, adding a number after the % will clear the % (entering % by hand will also clear it!!!)

Well, you could store the "real" textbox as a private string
private string realNumber = "";

public override string Text
{
get
{
return realNumber;
}
set
{
realNumber = value; // make sure this is a valid number without % base.Text = realNumber + "%";
}
}

Also, in the keypress event, set everything e.Handled = true;and if validchar add the character to realNumber;
Note: you will have to handle arrow keys and deletion insertion, cursor position

Or remove the ability to enter % and possibly prevent the user moving past the % (this would require handling END and arrow keys, but I bet it would look cool :p

--
Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/.

Nov 15 '05 #6
Jax,

Glad you got you new TextBox to work. I liked your idea, so I wrote my own.
I just though I would share my "Masked Edit Textbox" class example.
Source at end.
--
Glen Jones MCSD

public class PercentBox : System.Windows. Forms.TextBox
{
public PercentBox()
{
this.TextChange d += new EventHandler(Pe rcentBox_TextCh anged);
this.KeyPress += new KeyPressEventHa ndler(PercentBo x_KeyPress);
}
// Shorten code length
private void Log( string strTemp )
{
System.Diagnost ics.Debug.Write Line( strTemp );
}

private void PercentBox_Text Changed(object sender, System.EventArg s e)
{
// Get the current string and position
string strTemp = this.Text;
int intPos = this.SelectionS tart;

Log( "TextChange d [" + this.Name + "]" );
Log( " Text = '" + strTemp + "'" );
Log( " SelectionStart = " + intPos.ToString () );

// Now remove all % signs
strTemp = strTemp.Replace ( "%", "" );

// Add the percet to the end
strTemp += "%";

// Is the new text the same as what was there
if ( strTemp == this.Text )
// Don't set it or it will prevent endlessly loop
return;

// Remove event so when we change it doesn't call again
this.TextChange d -= new EventHandler (PercentBox_Tex tChanged);

// Set the new string
this.Text = strTemp;

// Add this event back
this.TextChange d += new EventHandler (PercentBox_Tex tChanged);

// Was the caret in the last position
if ( intPos >= strTemp.Length )
// Reset the position before the % sign,
// since setting the text reset it.
this.SelectionS tart = strTemp.Length - 1;
else
// Reset the position to were they were,
// since setting the text reset it.
this.SelectionS tart = intPos;
}

private void PercentBox_KeyP ress(object sender, KeyPressEventAr gs e)
{
Log( "KeyPress [" + this.Name + "]" );
Log( " KeyChar = '" + e.KeyChar + "' " +
((int)e.KeyChar ).ToString() );
Log( " Text = '" + this.Text + "'" );

// Are this key not allowed
if ( char.IsNumber( e.KeyChar ) == false &&
e.KeyChar != (char)8 &&
e.KeyChar != (char)'.' )
{
// Don't allow these keys
e.Handled = true;
return;
}

// Is this key a decimal
if ( e.KeyChar == (char)'.' )
{
// Do we already have a decimal in the string
if ( this.Text.Index Of( '.' ) >= 0 )
{
// Don't allow these keys
e.Handled = true;
return;
}
}
}
}
Nov 15 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

12
28569
by: Mosher | last post by:
Hi all, I have an issue with php and/or mysql. I have a php form that writes "items" to a mysql database, including a description of the item. On the mysql server, "magic_quotes_gpc" is ON. I am testing it now by putting special characters in the description field, this is what I am entering: O'Leary "special edition"
14
2663
by: David B. Held | last post by:
I wanted to post this proposal on c.l.c++.m, but my news server apparently does not support that group any more. I propose a new class of exception safety known as the "smart guarantee". Essentially, the smart guarantee promises to clean up resources whose ownership is passed into the function, for whatever defintion of "clean up" is most...
6
9738
by: kelvSYC | last post by:
This little bit of seeminly innocent code seems to give me these two errors, all on the line that declares check(). Is there some part of C++ that I'm missing out on? class Condition { public: Condition() {} virtual ~Condition() {} virtual bool check() const;
1
1398
by: knocte | last post by:
Hello group. In the following testcase I attach to the final of the message, I have two questions: 1) According to comment # 1, how can I pass an argument to the function that way? 2) According to comment # 2, why this special structure for the "for" statement is not working?
1
1606
by: Alessandro Bottoni | last post by:
Is there any module or interface that allow the programmer to access a imap4/pop3 server in a more pythonic (or Object Oriented) way than the usual imaplib and popolib? I mean: is there any module that would allow me to query the server for specific messages (and fetch them) in a way similar to a OODB? TIA ...
0
1981
by: Greg Bacchus | last post by:
Hi, Does anyone know how to make "special" folder apear under "My Computer". Like the Control Panel, or when a Camera appears when plugged in. And have it so that the contents of that folder is not actually part of the file structure anywhere on a disk, but made up by some program? Cheers Greg
8
3751
by: regis | last post by:
Greetings, about scanf matching nonempty sequences using the "%" matches a nonempty sequence of anything except '-' "%" matches a nonempty sequence of anything except ']" matches a nonempty sequence of anything except ']' "%" matches a nonempty sequence of anything except '^' "%" matches a nonempty sequence of '-' "%" matches a nonempty...
37
3920
by: jht5945 | last post by:
For example I wrote a function: function Func() { // do something } we can call it like: var obj = new Func(); // call it as a constructor or var result = Func(); // call it as a function
13
1932
by: Boris | last post by:
Can anyone tell me if Opera 9.5 is behaving correctly when wrapping the word C++, eg: C+ + Opera 9.2 didn't wrap C++. For those who use Opera 9.5 there is a test case at http://www.highscore.de/browsertest/cpp.html (try different window sizes until Opera 9.5 wraps C++).
0
217
by: Jon Skeet [C# MVP] | last post by:
On Sep 30, 12:35 pm, "John Straumann" <jstraum...@hotmail.comwrote: <snip> What's the encoding of the file? That's the first important thing to know. See http://pobox.com/~skeet/csharp/debuggingunicode.html
0
7918
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7843
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8220
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6621
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5713
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5392
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3840
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3875
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1452
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.