好的,我所有的代码都可以正常工作了。但是我无法在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
}
}
}
您可以使用正则表达式来验证您的输入
样例代码
private bool IsValidValue(string text)
{
bool isValid;
if (text.EndsWith("."))
{
text += "0";
}
if (Regex.IsMatch(text, @"^(\+|\-?)(((\d+)(.?)(\d+))|(\d+))$"))
{
isValid = true;
}
return isValid;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句