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 = ResultOfOtherThings();
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{allowedChars = value;}
}
// my override of text
public override string Text
{
get
{
if(base.Text.Length>1)
{
return base.Text.Substring(0, base.Text.Length-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.TextChanged += new EventHandler
(PercentBox_TextChanged);
this.KeyPress += new
System.Windows.Forms.KeyPressEventHandler
(PercentBox_KeyPress);
allowedChars = new ArrayList(10);
allowedChars.Add('0');
allowedChars.Add('1');
allowedChars.Add('2');
allowedChars.Add('3');
allowedChars.Add('4');
allowedChars.Add('5');
allowedChars.Add('6');
allowedChars.Add('7');
allowedChars.Add('8');
allowedChars.Add('9');
allowedChars.Add((char)8);
allowedChars.Add('.');
allowedChars.Add('%');
}
protected override void OnPaint(PaintEventArgs pe)
{
// TODO: Add custom paint code here
// Calling the base class OnPaint
base.OnPaint(pe);
}
private void PercentBox_TextChanged(object sender,
System.EventArgs e)
{
PercentBox pBox = (PercentBox) sender;
if(pBox.BaseText.Length>0)
{
// to make sure there only 1 % mark so the next if
//statement will work
string s = OnlyOneCharOfType(pBox.BaseText, '%');
if(s[s.Length-1] != '%')
{
// remove the eventhandler during the operation
this.TextChanged -= new EventHandler
(PercentBox_TextChanged);
string victim = pBox.BaseText;
// removes all '%' from victim
s = RemoveCharFromString(victim, '%');
// make sure there is only one decimal place
s = OnlyOneCharOfType(s, '.');
pBox.BaseText = s+"%";
this.TextChanged += new EventHandler
(PercentBox_TextChanged);
}
}
else
{
pBox.BaseText = "%";
}
}
private string OnlyOneCharOfType(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 RemoveCharFromString(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_KeyPress(object sender,
System.Windows.Forms.KeyPressEventArgs e)
{
char c = e.KeyChar;
if(!ValidatePressEntry(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 ValidatePressEntry(char c)
{
bool bob = false;
foreach(char okChar in allowedChars)
{
if(okChar == c)
{
bob = true;
}
}
return bob;
}
} 6 1597
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/
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.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/.
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.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.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/. .
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/
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.Add
((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/.
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.TextChanged += new EventHandler(PercentBox_TextChanged);
this.KeyPress += new KeyPressEventHandler(PercentBox_KeyPress);
}
// Shorten code length
private void Log( string strTemp )
{
System.Diagnostics.Debug.WriteLine( strTemp );
}
private void PercentBox_TextChanged(object sender, System.EventArgs e)
{
// Get the current string and position
string strTemp = this.Text;
int intPos = this.SelectionStart;
Log( "TextChanged [" + 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.TextChanged -= new EventHandler (PercentBox_TextChanged);
// Set the new string
this.Text = strTemp;
// Add this event back
this.TextChanged += new EventHandler (PercentBox_TextChanged);
// Was the caret in the last position
if ( intPos >= strTemp.Length )
// Reset the position before the % sign,
// since setting the text reset it.
this.SelectionStart = strTemp.Length - 1;
else
// Reset the position to were they were,
// since setting the text reset it.
this.SelectionStart = intPos;
}
private void PercentBox_KeyPress(object sender, KeyPressEventArgs 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.IndexOf( '.' ) >= 0 )
{
// Don't allow these keys
e.Handled = true;
return;
}
}
}
} This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
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...
|
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". ...
|
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:...
|
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)...
|
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...
|
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...
|
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...
|
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...
|
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...
|
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...
|
by: DolphinDB |
last post by:
Tired of spending countless mintues downsampling your data? Look no further!
In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
|
by: ryjfgjl |
last post by:
ExcelToDatabase: batch import excel into database automatically...
|
by: isladogs |
last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM).
In this month's session, we are pleased to welcome back...
|
by: isladogs |
last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM).
In this month's session, we are pleased to welcome back...
|
by: jfyes |
last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
|
by: PapaRatzi |
last post by:
Hello,
I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
|
by: CloudSolutions |
last post by:
Introduction:
For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
|
by: Defcon1945 |
last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
|
by: Faith0G |
last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
| |