确定我的所有代码都正常工作。但是我无法在textbox1和textbox3中输入小数位。我也只想在这些文本框中输入数字0-9。到目前为止,到目前为止,一切都在为我工作,但当我输入“。”我收到一个错误。我想一旦我得到小数就可以输入,我相信我也可以添加否定符号。我想我需要使用e.KeyChar正确吗?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace TemperatureConversion
{
/// <summary>
/// A program that turns Fahrenheit to Celsius.
/// </summary>
public partial class TemperatureConversionGYG : Form
{
// Varable for the calculatedCelsius output in textbox2
float calculatedCelsius;
// Varable for the Fahrenheit entered in textbox1.
float originalFahrenheit;
// Varable for the Celsius entered in textbox3.
float originalCelsius;
// Varable for the calculated fharenheit when user enters celsius to turn into fharenheit.
float calculatedTemperatureFahrenheit;
public TemperatureConversionGYG()
{
InitializeComponent();
}
public void button1_Click(object sender, EventArgs e)
{
// When this button is clicked it will use the number the user inputs in textbox1(FahrenheitNumber) to
// calculate the degree celsius and output it in textbox2.
calculatedCelsius = (originalFahrenheit - 32) / 9 * 5;
//Code here to send the calculatedCelsius to textbox2
textBox2.Text = calculatedCelsius.ToString();
}
public void textBox1_TextChanged(object sender, EventArgs e)
{
// originalFahrenheit that the program will read and convert it to a float when user inputs a number.
originalFahrenheit = Convert.ToInt32(textBox1.Text);
}
public void textBox2_TextChanged(object sender, EventArgs e)
{
// Need this box to accept 1 decimal. example 7.2, 55.5, 99
}
private void Twitter_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
// Navigate to a URL.
System.Diagnostics.Process.Start("https://twitter.com/GYGamers");
}
private void textBox3_TextChanged(object sender, EventArgs e)
{
// originalCelsius that the program will read and convert it to a float when user inputs a number.
originalCelsius = Convert.ToInt32(textBox3.Text);
}
private void button2_Click(object sender, EventArgs e)
{
// This turns origianlCelsius to Fahrenheit.
calculatedTemperatureFahrenheit = (originalCelsius * 9) / 5 + 32;
//Code here to send the calculatedTemperatureFahrenheit to textbox4
textBox4.Text = calculatedTemperatureFahrenheit.ToString();
}
private void textBox4_TextChanged(object sender, EventArgs e)
{
// Need this box to accept 1 decimal. example 7.2, 55.5, 99
}
}
}
答案 0 :(得分:0)
您可以使用Regex表达式验证输入
示例代码
private bool IsValidValue(string text)
{
bool isValid;
if (text.EndsWith("."))
{
text += "0";
}
if (Regex.IsMatch(text, @"^(\+|\-?)(((\d+)(.?)(\d+))|(\d+))$"))
{
isValid = true;
}
return isValid;
}