e.keychar返回ascii值。我如何获得char/int值?
问题描述:
Iam试图从e.KeyChar获得interget值,但它只是给了我ascii值。e.keychar返回ascii值。我如何获得char/int值?
为了缩短。
int[] row = {1,2,3};
private void Inputnr1box_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
else if (row.Contains(e.KeyChar)) { MessageBox.Show("Well done boys");
}
else { MessageBox.Show("Fail!"); }
}
,如果我尝试在我的阵列,以改变一个值,说49和发送“1”一切都很好。
该问题起源于一组较大的文本框,用户可以放置数值但不允许输入重复值。我计划将这些值保存在一个整数数组中,然后使用contains来查看它是否已经输入过一次。
答
您可以执行以下操作来确定按下的键是否是数字,如果数字不在那里,则处理。
List<int> row = new List<int>();
private void Inputnr1box_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
{
e.Handled = true; // Not a DIGIT
}
else
{
// Else test for existence
int number;
if (Int32.TryParse(e.KeyChar.ToString(), out number))
{
if (row.Contains(number))
{
e.Handled = true; // Already exists
}
else
{
row.Add(number);
}
}
}
}
+1
这似乎工作,并且比我终于想出的那个更漂亮一点。 真的屁股我,我必须转换为字符串,然后回到int来获得“正常”int。 谢谢你真的很高兴你。 – Jacob 2015-01-21 04:42:35
减去48并检查它的范围是0-9。 – PeterJ 2015-01-21 03:52:28
@PeterJ - 这实际上是一个非常好的主意。尽管我的想法是为更像KCdod的解决方案而设定的,所以我就这样做了。 谢谢! – Jacob 2015-01-21 04:37:24