c# - 在文本框中只输入字母,也只用一个减号 (-) 最好使用 ASCII 码
问题描述
我想使用减号的ASCII 码。有没有可能的方法呢?只使用一次减号。 45是减号 (-) 的 ASCII 码
private void txtcity_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = !(char.IsLetter(e.KeyChar) || e.KeyChar == (char)Keys.Back);// e.KeyChar == (char)Keys.45);
}
解决方案
要只允许使用连字符/减号一次,您需要检查 TextBox 是否已经包含一个。如果是,则设置e.Handled
为 true。您的其余逻辑应该可以正常工作。
你可以使用这样的东西:
private void txtcity_KeyPress(object sender, KeyPressEventArgs e)
{
// If you want to use the ASCII code, for some reason.
const int minusAsciiCode = 45;
// if (e.KeyChar == '-')
if (e.KeyChar == (char)minusAsciiCode)
{
e.Handled = txtcity.Text.Contains("-");
}
else
{
e.Handled = !(char.IsLetter(e.KeyChar) || e.KeyChar == (char)Keys.Back);
}
}
推荐阅读
- neo4j - GraphQL 与 Bolt - Neo4j
- excel - 有条件地将记录移动到新 wksheets 的问题
- android - 通过`Dispatchers.IO`启动协程时出现NetworkOnMainThreadException
- sql - 如何使用递归 CTE 查询避免急切的假脱机?
- elisp - 定义 elisp 函数,获取 2 个列表并返回列表 1 中的原子在列表 2 中出现的次数
- php - 在 WooCommerce 中向非会员显示会员折扣价
- java - 如何修复 Java AVL 树插入/平衡不正确
- css - 如何使用未包含在反应代码中的悬停?
- angular - 如何通过HttpClient调用服务来初始化组件数据
- arduino - 适合远距离读写的 RFID 模块和标签