I want to enter floating point values to some of the record. So if i enter .(decimal point), the zero should be added before the decimal point. For example (开发者_运维百科if i enter .2 into the textbox, it has to display like 0.2). How it can be done?
Any help will be appreciated.
Anticipated thanks.
Just parse the string to a double, and convert it back to string, then it will be formatted with a leading zero. Example:
string input = ".42";
double value = Double.Parse(input, CultureInfo.InvariantCulture);
string display = value.ToString(CultureInfo.InvariantCulture);
The string display
now contains "0.42"
.
You might want to use the Double.TryParse
method to handle when the input is not valid.
Assuming a textbox, in it's properties, go to events, double-click on Leave (Listed below focus). A function is generated, write a simple if structure inside it similar to one below:
private void textBox1_Leave(object sender, EventArgs e)
{
if ((textBox1.Text.Trim()).StartsWith("."))
textBox1.Text = "0" + textBox1.Text;
}
keypressevent
// add zero before point
public void addzerobefore(object sender, KeyPressEventArgs e)
{
TextBox add0txtbx = sender as TextBox;
if ((add0txtbx.Text.Trim()).StartsWith("."))
{
add0txtbx.Text = "0"+add0txtbx.Text;
add0txtbx.Select(add0txtbx.Text.Length, 0);
}
}
精彩评论