我正在做一个新的整数框,我希望它只接受整数和指数E.我知道做指数E你必须做Math.Exp(x)但我似乎无法找到把它放在正确的地方。有人可以帮帮我吗?
namespace IntegerBox
{
public partial class IntBox : TextBox
{
private double intNum;
public double IntNum
{
get { return intNum; }
set { intNum = value; }
}
public IntBox()
{ // set initial values to prperty Text, Event handlers properties TextChanged, Leave
this.Text = "0";
this.TextChanged += new EventHandler(IntBox_TextChanged);
this.Leave += new EventHandler(IntBox_Leave);
this.Math.Exp();
InitializeComponent();
}
protected void IntBox_TextChanged(object sender, EventArgs e)
{
try
{
IntNum = Convert.ToDouble(this.Text);
Math.Exp(intNum);
}
catch (FormatException)
{
MessageBox.Show("Other than Integer number entered",
"Your error was",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
protected void IntBox_Leave(object sender, EventArgs e)
{
intNum = Convert.ToDouble(this.Text);
Math.Exp(intNum);
//intNum = Math.Exp(this.Text);
}
protected override void OnPaint(PaintEventArgs pe)
{
base.OnPaint(pe);
}
private void IntBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyValue == 13)
{
intNum = Convert.ToDouble(this.Text);
Math.Exp(intNum);
// intNum = Math.Exp(this.Text);
}
}
}
}
答案 0 :(得分:0)
首先,既然你想获得一个整数值,你应该这样声明:
// use Int64 to allow larger numbers. Otherwise stick to the classic int type
private Int64 intNum;
public Int64 IntNum
{
get { return intNum; }
set { intNum = value; }
}
我假设你想允许接近科学记数法(即指数为E的数字)给你的整数值,因为E数是双值。
try
{
IntNum = Convert.ToDouble(this.Text);
Math.Exp(intNum);
}
可以成为
try
{
IntNum = ConvertToInt64(Convert.ToDouble(this.Text));
}
catch (...)
{
}
您将获得out of range values
和invalid format
的不同例外,因此仅仅处理FormatException是不够的。
整个解决方案的另一个方面是其复杂性。考虑使用Binding,因为这将自动处理数据传输(从属性到控制,反之亦然)。