C# 非数值数据的错误检查
我希望有人能帮我检查粘贴方法的错误。我希望防止将剪贴板中非数值的任何内容粘贴到我的文本框中。粘贴的编码如下所示C# 非数值数据的错误检查,c#,copy-paste,error-checking,C#,Copy Paste,Error Checking,我希望有人能帮我检查粘贴方法的错误。我希望防止将剪贴板中非数值的任何内容粘贴到我的文本框中。粘贴的编码如下所示 private void pasteToolStripMenuItem_Click(object sender, EventArgs e) { // Determine if there is any text in the Clipboard to paste into the text box.
private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
{
// Determine if there is any text in the Clipboard to paste into the text box.
if (Clipboard.GetDataObject().GetDataPresent(DataFormats.Text) == true)
{
// Determine if any text is selected in the text box.
if (textBox1.SelectionLength > 0)
{
// Ask user if they want to paste over currently selected text.
if (MessageBox.Show("Do you want to paste over current selection?", "Cut Example", MessageBoxButtons.YesNo) == DialogResult.No)
// Move selection to the point after the current selection and paste.
textBox1.SelectionStart = textBox1.SelectionStart + textBox1.SelectionLength;
} // end if
} // Paste current text in Clipboard into text box.
textBox1.Paste();
} // end pasteToolStripMenuItem
如果您想包括
货币符号
,小数位
,千位分隔符
等。Int.Parse
可能是您最好的选择
public bool IsValidNumber(string input)
{
int val = 0;
return int.TryParse(input.Trim(), NumberStyles.Any, null, out val);
}
"$100,000" = true
"100.002" = true
"1000,44j" = false
etc.
您想阻止用户粘贴,还是希望用户能够粘贴但自动删除非数字数据?现在您可以将任何需要的内容粘贴到文本框中。如果您试图粘贴“abc”,我希望出现一条错误消息,那么有没有任何不是数字的内容关于Ctrl+V呢?文本框上下文菜单上的粘贴命令如何?不要这样写代码。改为使用验证事件。@HansPassant-对不起,我不太明白你的意思?我两周前才开始读C:)数字是否包括符号、小数点、千位分隔符?更新后允许使用有效的数字符号