pendragon Posted December 26, 2003 Posted December 26, 2003 I am writing a user control for number input, It also has a new property for the number of decimal places allowed and will not let you enter more than is specified. Here is what I have so far. using System; using System.Windows.Forms; namespace NumberDecimals { public class Number : TextBox { private int noOfDecimals; public int NoOfDecimals { get { return this.noOfDecimals; } set { this.noOfDecimals = value; } } public Number() { } protected override void OnKeyPress(KeyPressEventArgs e) { base.OnKeyPress(e); if(this.noOfDecimals == 0) { if(Char.IsNumber(e.KeyChar) || e.KeyChar == (char)8) { e.Handled = false; } else { e.Handled = true; } } else { bool bFoundDecimal = false; string sNumber, sSelected; int iCount, iLength, iNoAfterDecimal, iDecimalPosition; sSelected = this.SelectedText; sNumber = this.Text; iLength = this.TextLength; iDecimalPosition = 0; if (e.KeyChar == (char)46) { if (sSelected != sNumber) { for (iCount = 0; iCount < iLength; iCount++) { if (sNumber.Substring(iCount,1) == ".") { bFoundDecimal = true; iCount = iLength; } } if(bFoundDecimal == true) { e.Handled = true; } else { e.Handled = false; } } else { e.Handled = false; } } else if (Char.IsNumber(e.KeyChar) || e.KeyChar == (char)8) { iDecimalPosition = iLength; for (iCount = 0; iCount < iLength; iCount++) { if (sNumber.Substring(iCount,1) == ".") { iDecimalPosition = iCount; iCount = iLength; } } if (iDecimalPosition == iLength || sSelected == sNumber) { e.Handled = false; } else { iNoAfterDecimal = iLength - iDecimalPosition; if (iNoAfterDecimal <= this.noOfDecimals || e.KeyChar == (char)8) { e.Handled = false; } else { e.Handled = true; } } } else { e.Handled = true; } } } } } This all works to a point. If NoOfDecimals is set to 2 and 123.45 has been entered into the textbox, if the user whats to change it to 1123.45 then at the moment they have to remove the .45 before anything else can be entered. Is there a way of finding the current postion of the curser in the textbox so I can check to see if it is to the left of the decimal. Thank You. Quote
*Experts* Bucky Posted December 27, 2003 *Experts* Posted December 27, 2003 Yes, use the SelectionStart property. Quote "Being grown up isn't half as fun as growing up These are the best days of our lives" -The Ataris, In This Diary
pendragon Posted December 27, 2003 Author Posted December 27, 2003 Thanks for that Bucky. I thought SelectionStart was only set when you had highlighted some text, you learn something new every day.:D Quote
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.