大一新生写的一个小程序,有BUG,始终无法解决这个BUG,求助 本帖最后由 dsb2468 于 2013-01-29 22:33:38 编辑 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 把源代码贴出来,发exe有什么用。 看下你的TextChanged事件里写了什么的 那里出的问题 附上源代码: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 suzu{ public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { button1.Enabled = false; } private void textBox1_TextChanged(object sender, EventArgs e) { if (textBox1.Text == "") button1.Enabled = false; else button1.Enabled = true; foreach (char c in textBox1.Text) { if (c >= '0' && c <= '9' || c == '.' || c == '|') { //控制除数字以外可以输入"|","." } //else if (!IsDigit(textBox1.Text)) //这里不调用也可以但是如果大量文本框需要控制是否为数字就需要调用 //{ // MessageBox.Show("输入不能包含与非计算无关的字符", "错误提示"); // textBox1.Text = textBox1.Text.Substring(0, textBox1.TextLength - 1); // textBox1.Focus(); //} else { MessageBox.Show("输入不能包含与非计算无关的字符", "错误提示"); textBox1.Text = textBox1.Text.Substring(0, textBox1.TextLength - 1); textBox1.Focus(); } } ////textBox1.Text=textBox1.Text.Trim(); 貌似是去掉空格用的。这个程序里并未用到 } /// <summary> /// 这里便是调用检查文本框是否为数字(这里的数字是指“整型”的数字) /// </summary> /// <param name="str"></param> /// <returns></returns> public bool IsDigit(string str) { string subs = ""; for (int i = 0; i < str.Length; i++) { subs = str.Substring(i, 1); if (!char.IsNumber(char.Parse(subs))) { return false; } } return true; } private void button1_Click(object sender, EventArgs e) { if (textBox1.Text == "") { MessageBox.Show("请输入成绩按回车结束或者点击计算按钮"); } else { string[] mnber = textBox1.Text.Split('|'); int n = 0; for (int i = 0; i < mnber.Length; i++) { try { if (double.Parse(mnber[i]) < 60) { n++; } } catch { MessageBox.Show("运算出现非法字符", "错误"); textBox1.Text = ""; textBox1.Focus(); break; } } label2.Text = "不及格的人数是:" + n.ToString() + "个"; } } private void textBox1_KeyPress(object sender, KeyPressEventArgs e) { if (Convert.ToInt32(e.KeyChar) == 13) { if (textBox1.Text == "") { MessageBox.Show("请你输入成绩按回车结束或者点击计算按钮"); } else { string[] mnber = textBox1.Text.Split('|'); int n = 0; for (int i = 0; i < mnber.Length; i++) { try { if (double.Parse(mnber[i]) < 60) { n++; } } catch { MessageBox.Show("运算出现非法字符","错误"); textBox1.Text = ""; textBox1.Focus(); break; } } label2.Text = "不及格的人数是:" + n.ToString() + "个"; } } } }} 附上源代码: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 suzu{ public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { button1.Enabled = false; } private void textBox1_TextChanged(object sender, EventArgs e) { if (textBox1.Text == "") button1.Enabled = false; else button1.Enabled = true; foreach (char c in textBox1.Text) { if (c >= '0' && c <= '9' || c == '.' || c == '|') { //控制除数字以外可以输入"|","." } //else if (!IsDigit(textBox1.Text)) //这里不调用也可以但是如果大量文本框需要控制是否为数字就需要调用 //{ // MessageBox.Show("输入不能包含与非计算无关的字符", "错误提示"); // textBox1.Text = textBox1.Text.Substring(0, textBox1.TextLength - 1); // textBox1.Focus(); //} else { MessageBox.Show("输入不能包含与非计算无关的字符", "错误提示"); textBox1.Text = textBox1.Text.Substring(0, textBox1.TextLength - 1); textBox1.Focus(); } } ////textBox1.Text=textBox1.Text.Trim(); 貌似是去掉空格用的。这个程序里并未用到 } /// <summary> /// 这里便是调用检查文本框是否为数字(这里的数字是指“整型”的数字) /// </summary> /// <param name="str"></param> /// <returns></returns> public bool IsDigit(string str) { string subs = ""; for (int i = 0; i < str.Length; i++) { subs = str.Substring(i, 1); if (!char.IsNumber(char.Parse(subs))) { return false; } } return true; } private void button1_Click(object sender, EventArgs e) { if (textBox1.Text == "") { MessageBox.Show("请输入成绩按回车结束或者点击计算按钮"); } else { string[] mnber = textBox1.Text.Split('|'); int n = 0; for (int i = 0; i < mnber.Length; i++) { try { if (double.Parse(mnber[i]) < 60) { n++; } } catch { MessageBox.Show("运算出现非法字符", "错误"); textBox1.Text = ""; textBox1.Focus(); break; } } label2.Text = "不及格的人数是:" + n.ToString() + "个"; } } private void textBox1_KeyPress(object sender, KeyPressEventArgs e) { if (Convert.ToInt32(e.KeyChar) == 13) { if (textBox1.Text == "") { MessageBox.Show("请你输入成绩按回车结束或者点击计算按钮"); } else { string[] mnber = textBox1.Text.Split('|'); int n = 0; for (int i = 0; i < mnber.Length; i++) { try { if (double.Parse(mnber[i]) < 60) { n++; } } catch { MessageBox.Show("运算出现非法字符","错误"); textBox1.Text = ""; textBox1.Focus(); break; } } label2.Text = "不及格的人数是:" + n.ToString() + "个"; } } } }} 附上源代码: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 suzu{ public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { button1.Enabled = false; } private void textBox1_TextChanged(object sender, EventArgs e) { if (textBox1.Text == "") button1.Enabled = false; else button1.Enabled = true; foreach (char c in textBox1.Text) { if (c >= '0' && c <= '9' || c == '.' || c == '|') { //控制除数字以外可以输入"|","." } //else if (!IsDigit(textBox1.Text)) //这里不调用也可以但是如果大量文本框需要控制是否为数字就需要调用 //{ // MessageBox.Show("输入不能包含与非计算无关的字符", "错误提示"); // textBox1.Text = textBox1.Text.Substring(0, textBox1.TextLength - 1); // textBox1.Focus(); //} else { MessageBox.Show("输入不能包含与非计算无关的字符", "错误提示"); textBox1.Text = textBox1.Text.Substring(0, textBox1.TextLength - 1); textBox1.Focus(); } } ////textBox1.Text=textBox1.Text.Trim(); 貌似是去掉空格用的。这个程序里并未用到 } /// <summary> /// 这里便是调用检查文本框是否为数字(这里的数字是指“整型”的数字) /// </summary> /// <param name="str"></param> /// <returns></returns> public bool IsDigit(string str) { string subs = ""; for (int i = 0; i < str.Length; i++) { subs = str.Substring(i, 1); if (!char.IsNumber(char.Parse(subs))) { return false; } } return true; } private void button1_Click(object sender, EventArgs e) { if (textBox1.Text == "") { MessageBox.Show("请输入成绩按回车结束或者点击计算按钮"); } else { string[] mnber = textBox1.Text.Split('|'); int n = 0; for (int i = 0; i < mnber.Length; i++) { try { if (double.Parse(mnber[i]) < 60) { n++; } } catch { MessageBox.Show("运算出现非法字符", "错误"); textBox1.Text = ""; textBox1.Focus(); break; } } label2.Text = "不及格的人数是:" + n.ToString() + "个"; } } private void textBox1_KeyPress(object sender, KeyPressEventArgs e) { if (Convert.ToInt32(e.KeyChar) == 13) { if (textBox1.Text == "") { MessageBox.Show("请你输入成绩按回车结束或者点击计算按钮"); } else { string[] mnber = textBox1.Text.Split('|'); int n = 0; for (int i = 0; i < mnber.Length; i++) { try { if (double.Parse(mnber[i]) < 60) { n++; } } catch { MessageBox.Show("运算出现非法字符","错误"); textBox1.Text = ""; textBox1.Focus(); break; } } label2.Text = "不及格的人数是:" + n.ToString() + "个"; } } } }} 把foreach循环改成其他的任意循环就可以了,for,while,do while,随你高兴基础没学好,foreach循环不能对集合进行删除操作的 可是程序可以运行啊,只是如果复制一段文字到框里,最终就会报错,。难道这是FOREACH的原因? 错误是substring下标越界,不过你的代码太烂了,废话好多,bug成群,直接用我在另一个帖给你的代码吧。 private void textBox1_TextChanged(object sender, EventArgs e) { if (System.Text.RegularExpressions.Regex.IsMatch(textBox1.Text.Trim(), @"^(\d+(\.\d+)?(\||$))+$")) { } else { MessageBox.Show("输入不能包含与非计算无关的字符", "错误提示"); textBox1.Text = ""; } } 这句有问题:textBox1.Text = textBox1.Text.Substring(0, textBox1.TextLength - 1);//1、外层使用了foreach,textBox1.Text就变成ReadOnly了,不能改动。//2、如果textBox1.TextLength == 0,textBox1.TextLength - 1则会报数组越界的错误。 呵呵,你的代码虽然有点乱,但是看了一下,整个代码架构没有出现一次的错误处理,一旦发生错误,立马崩溃,复制东西进去,正如上面所说的,错误原因已经很明显了还有MessageBox.Show("输入不能包含与非计算无关的字符", "错误提示");textBox1.Text = textBox1.Text.Substring(0, textBox1.TextLength - 1);textBox1.Focus();就算你这段代码合理,既然都已经出现错误了,就应该跳出来了,为什么还要继续?况且你这段代码写的也不合理,假如字符串长度为0,你这个就报错了个人见解 private bool IsDigit(string str){ return (Regex.IsMatch(str, @"^[0-9]+$"));} 根本原因已经告诉你了,foreach循环不能对集合惊醒删除操作,你程序运行的时候又没进行删除操作当然不会报错你把foreach循环换了就好了,其他代码都不用改 Try{}catch(exception){}then 百度,msdn,csdn 你的代码是实现文本框的输入限制吗?这样做思路是有问题的,本手应该是通过消息控制。下面是一个限制只能输入数字、正负符号的控件代码供参考 /// <summary> /// 数字输入文本框,仅可输入整数或小数 /// </summary> [Description("数字输入文本框,仅可输入整数或小数")] [ToolboxBitmap("NumericTextBox.bmp")] public class NumericTextBox: TextBox { private int _dotCount = 0; //小数位数 private bool _positive = false; //是否允许输入负数 private bool _isValidChar = false; //输入的是否是合法字符 private string _validStr = "0123456789."; //合法的字符数组字符串(默认不许输入负数) /// <summary> /// 小数部分的最大长度,如果小于 0,表示可以输入任何字符 /// </summary> [Description("小数部分的最大长度,如果小于 0,表示可以输入任何字符"), Browsable(true), DefaultValue(0)] public int DotCount { get { return _dotCount; } set { if (value < -1 || value > this.MaxLength) throw new Exception("小数部分长度必须介于 -1 到 " + this.MaxLength.ToString() + " 之间。"); _dotCount = value; if (!Validate(this.Text)) this.Text = ""; } } /// 是否允许输入负数 /// <summary> /// 是否允许输入负数 /// </summary> [Description("是否允许输入负数"), Browsable(true), DefaultValue(false)] public bool Positive { get { return _positive; } set { _positive = value; if (_positive) _validStr = "0123456789-."; else _validStr = "0123456789."; } } /// 验证数据是否合法 /// <summary> /// 验证数据是否合法 /// </summary> /// <param name="str">要验证的字符串</param> /// <returns></returns> private bool Validate(string str) { //如果 _DotCount == -1,或字符串为空,不再验证,可以输入任何字符 if (_dotCount <= -1 || str == "") return true; string str1 = this.Text.Substring(0, this.SelectionStart); string str2 = this.Text.Substring(this.SelectionStart, this.Text.Length - this.SelectionLength - this.SelectionStart); str = str1 + str + str2; //如果结果仅仅是“+”或“-”,允许输入 if (str == "+" || str == "-") return true; //判断是否可以转换成数字 double doubleValue = 0; if (!double.TryParse(str, out doubleValue)) return false; //如果小数位数为 0,表示只能输入整数 if (_dotCount == 0) return str.IndexOf('.') < 0; //判断小数位数是否超过了指定的长度 int dotIndex = str.IndexOf('.'); if (dotIndex >= 0 && str.Length - dotIndex - 1 > _dotCount) return false; return true; } /// 重写 OnKeyDown 函数,处理按键 /// <summary> /// 重写 OnKeyDown 函数,处理按键 /// </summary> /// <param name="e"></param> protected override void OnKeyDown(KeyEventArgs e) { _isValidChar = false; //系统默认快捷键的处理 if ((e.Control && e.KeyCode == Keys.C) //复制 || (e.Control && e.KeyCode == Keys.Z) //撤销 || (e.Control && e.KeyCode == Keys.V) //粘贴 || (e.Control && e.KeyCode == Keys.X) //剪切 || e.KeyCode == Keys.Back) //退格 _isValidChar = true; else _isValidChar = false; base.OnKeyDown(e); } /// 重写的 OnkeyPress 函数,处理按键 /// <summary> /// 重写的 OnkeyPress 函数,处理按键 /// </summary> /// <param name="e"></param> protected override void OnKeyPress(KeyPressEventArgs e) { if (!_isValidChar) { if (_dotCount > -1 && _validStr.IndexOf(e.KeyChar) < 0) e.Handled = true; else e.Handled = !Validate(e.KeyChar.ToString()); } base.OnKeyPress(e); } /// 重写粘贴消息,非法的字符不能粘贴 /// <summary> /// 重写粘贴消息,非法的字符不能粘贴 /// </summary> /// <param name="m"></param> protected override void WndProc(ref Message m) { if (m.Msg == 0x0302) { string clipStr = Clipboard.GetText(); if(!Validate(clipStr)) return; } base.WndProc(ref m); } } 菜鸟求解。。。。截取字符串问题 求助:WinForm绘图,一个图上面N个活动的点,每个点代表一个人或设备,求建议 关于《软件工程》这门课的问题 c#如何修改多个文本文件内容 [===============]去掉字符串 数字后的单位 C#中如何在RichTextBox中实现背景图案?100分! 急求高人指教。。。 C#中我非常搞不明白的问题 高手来帮忙 [急]VML工作流设计器显示模型图的问题 冰天雪地跪求如何利用C#将XML文件作为一个整体存入sql2005的xml字段中 C#如何向excel文件中插入另一个excel表 combox.selectindex=-1 不能初始化下拉框
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 suzu
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void Form1_Load(object sender, EventArgs e)
{
button1.Enabled = false;
} private void textBox1_TextChanged(object sender, EventArgs e)
{
if (textBox1.Text == "")
button1.Enabled = false;
else
button1.Enabled = true;
foreach (char c in textBox1.Text)
{
if (c >= '0' && c <= '9' || c == '.' || c == '|')
{
//控制除数字以外可以输入"|","."
}
//else if (!IsDigit(textBox1.Text)) //这里不调用也可以但是如果大量文本框需要控制是否为数字就需要调用
//{
// MessageBox.Show("输入不能包含与非计算无关的字符", "错误提示");
// textBox1.Text = textBox1.Text.Substring(0, textBox1.TextLength - 1);
// textBox1.Focus();
//}
else
{
MessageBox.Show("输入不能包含与非计算无关的字符", "错误提示");
textBox1.Text = textBox1.Text.Substring(0, textBox1.TextLength - 1);
textBox1.Focus();
}
}
////textBox1.Text=textBox1.Text.Trim(); 貌似是去掉空格用的。这个程序里并未用到
} /// <summary>
/// 这里便是调用检查文本框是否为数字(这里的数字是指“整型”的数字)
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public bool IsDigit(string str)
{
string subs = "";
for (int i = 0; i < str.Length; i++)
{
subs = str.Substring(i, 1);
if (!char.IsNumber(char.Parse(subs)))
{
return false;
}
}
return true;
} private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text == "")
{
MessageBox.Show("请输入成绩按回车结束或者点击计算按钮");
}
else
{
string[] mnber = textBox1.Text.Split('|');
int n = 0;
for (int i = 0; i < mnber.Length; i++)
{
try
{
if (double.Parse(mnber[i]) < 60)
{
n++;
}
}
catch
{
MessageBox.Show("运算出现非法字符", "错误");
textBox1.Text = "";
textBox1.Focus();
break;
}
}
label2.Text = "不及格的人数是:" + n.ToString() + "个";
}
} private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (Convert.ToInt32(e.KeyChar) == 13)
{
if (textBox1.Text == "")
{
MessageBox.Show("请你输入成绩按回车结束或者点击计算按钮");
} else
{
string[] mnber = textBox1.Text.Split('|');
int n = 0;
for (int i = 0; i < mnber.Length; i++)
{
try
{
if (double.Parse(mnber[i]) < 60)
{
n++;
}
}
catch
{
MessageBox.Show("运算出现非法字符","错误");
textBox1.Text = "";
textBox1.Focus();
break;
}
}
label2.Text = "不及格的人数是:" + n.ToString() + "个";
}
}
}
}
}
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 suzu
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void Form1_Load(object sender, EventArgs e)
{
button1.Enabled = false;
} private void textBox1_TextChanged(object sender, EventArgs e)
{
if (textBox1.Text == "")
button1.Enabled = false;
else
button1.Enabled = true;
foreach (char c in textBox1.Text)
{
if (c >= '0' && c <= '9' || c == '.' || c == '|')
{
//控制除数字以外可以输入"|","."
}
//else if (!IsDigit(textBox1.Text)) //这里不调用也可以但是如果大量文本框需要控制是否为数字就需要调用
//{
// MessageBox.Show("输入不能包含与非计算无关的字符", "错误提示");
// textBox1.Text = textBox1.Text.Substring(0, textBox1.TextLength - 1);
// textBox1.Focus();
//}
else
{
MessageBox.Show("输入不能包含与非计算无关的字符", "错误提示");
textBox1.Text = textBox1.Text.Substring(0, textBox1.TextLength - 1);
textBox1.Focus();
}
}
////textBox1.Text=textBox1.Text.Trim(); 貌似是去掉空格用的。这个程序里并未用到
} /// <summary>
/// 这里便是调用检查文本框是否为数字(这里的数字是指“整型”的数字)
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public bool IsDigit(string str)
{
string subs = "";
for (int i = 0; i < str.Length; i++)
{
subs = str.Substring(i, 1);
if (!char.IsNumber(char.Parse(subs)))
{
return false;
}
}
return true;
} private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text == "")
{
MessageBox.Show("请输入成绩按回车结束或者点击计算按钮");
}
else
{
string[] mnber = textBox1.Text.Split('|');
int n = 0;
for (int i = 0; i < mnber.Length; i++)
{
try
{
if (double.Parse(mnber[i]) < 60)
{
n++;
}
}
catch
{
MessageBox.Show("运算出现非法字符", "错误");
textBox1.Text = "";
textBox1.Focus();
break;
}
}
label2.Text = "不及格的人数是:" + n.ToString() + "个";
}
} private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (Convert.ToInt32(e.KeyChar) == 13)
{
if (textBox1.Text == "")
{
MessageBox.Show("请你输入成绩按回车结束或者点击计算按钮");
} else
{
string[] mnber = textBox1.Text.Split('|');
int n = 0;
for (int i = 0; i < mnber.Length; i++)
{
try
{
if (double.Parse(mnber[i]) < 60)
{
n++;
}
}
catch
{
MessageBox.Show("运算出现非法字符","错误");
textBox1.Text = "";
textBox1.Focus();
break;
}
}
label2.Text = "不及格的人数是:" + n.ToString() + "个";
}
}
}
}
}
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 suzu
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void Form1_Load(object sender, EventArgs e)
{
button1.Enabled = false;
} private void textBox1_TextChanged(object sender, EventArgs e)
{
if (textBox1.Text == "")
button1.Enabled = false;
else
button1.Enabled = true;
foreach (char c in textBox1.Text)
{
if (c >= '0' && c <= '9' || c == '.' || c == '|')
{
//控制除数字以外可以输入"|","."
}
//else if (!IsDigit(textBox1.Text)) //这里不调用也可以但是如果大量文本框需要控制是否为数字就需要调用
//{
// MessageBox.Show("输入不能包含与非计算无关的字符", "错误提示");
// textBox1.Text = textBox1.Text.Substring(0, textBox1.TextLength - 1);
// textBox1.Focus();
//}
else
{
MessageBox.Show("输入不能包含与非计算无关的字符", "错误提示");
textBox1.Text = textBox1.Text.Substring(0, textBox1.TextLength - 1);
textBox1.Focus();
}
}
////textBox1.Text=textBox1.Text.Trim(); 貌似是去掉空格用的。这个程序里并未用到
} /// <summary>
/// 这里便是调用检查文本框是否为数字(这里的数字是指“整型”的数字)
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public bool IsDigit(string str)
{
string subs = "";
for (int i = 0; i < str.Length; i++)
{
subs = str.Substring(i, 1);
if (!char.IsNumber(char.Parse(subs)))
{
return false;
}
}
return true;
} private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text == "")
{
MessageBox.Show("请输入成绩按回车结束或者点击计算按钮");
}
else
{
string[] mnber = textBox1.Text.Split('|');
int n = 0;
for (int i = 0; i < mnber.Length; i++)
{
try
{
if (double.Parse(mnber[i]) < 60)
{
n++;
}
}
catch
{
MessageBox.Show("运算出现非法字符", "错误");
textBox1.Text = "";
textBox1.Focus();
break;
}
}
label2.Text = "不及格的人数是:" + n.ToString() + "个";
}
} private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (Convert.ToInt32(e.KeyChar) == 13)
{
if (textBox1.Text == "")
{
MessageBox.Show("请你输入成绩按回车结束或者点击计算按钮");
} else
{
string[] mnber = textBox1.Text.Split('|');
int n = 0;
for (int i = 0; i < mnber.Length; i++)
{
try
{
if (double.Parse(mnber[i]) < 60)
{
n++;
}
}
catch
{
MessageBox.Show("运算出现非法字符","错误");
textBox1.Text = "";
textBox1.Focus();
break;
}
}
label2.Text = "不及格的人数是:" + n.ToString() + "个";
}
}
}
}
}
错误是substring下标越界,不过你的代码太烂了,废话好多,bug成群,直接用我在另一个帖给你的代码吧。
{
if (System.Text.RegularExpressions.Regex.IsMatch(textBox1.Text.Trim(), @"^(\d+(\.\d+)?(\||$))+$"))
{ }
else
{
MessageBox.Show("输入不能包含与非计算无关的字符", "错误提示");
textBox1.Text = "";
}
}
textBox1.Text = textBox1.Text.Substring(0, textBox1.TextLength - 1);
//1、外层使用了foreach,textBox1.Text就变成ReadOnly了,不能改动。
//2、如果textBox1.TextLength == 0,textBox1.TextLength - 1则会报数组越界的错误。
MessageBox.Show("输入不能包含与非计算无关的字符", "错误提示");
textBox1.Text = textBox1.Text.Substring(0, textBox1.TextLength - 1);
textBox1.Focus();
就算你这段代码合理,既然都已经出现错误了,就应该跳出来了,为什么还要继续?况且你这段代码写的也不合理,假如字符串长度为0,你这个就报错了个人见解
{
return (Regex.IsMatch(str, @"^[0-9]+$"));
}
根本原因已经告诉你了,foreach循环不能对集合惊醒删除操作,你程序运行的时候又没进行删除操作当然不会报错你把foreach循环换了就好了,其他代码都不用改
下面是一个限制只能输入数字、正负符号的控件代码供参考 /// <summary>
/// 数字输入文本框,仅可输入整数或小数
/// </summary>
[Description("数字输入文本框,仅可输入整数或小数")]
[ToolboxBitmap("NumericTextBox.bmp")]
public class NumericTextBox: TextBox
{
private int _dotCount = 0; //小数位数
private bool _positive = false; //是否允许输入负数 private bool _isValidChar = false; //输入的是否是合法字符
private string _validStr = "0123456789."; //合法的字符数组字符串(默认不许输入负数) /// <summary>
/// 小数部分的最大长度,如果小于 0,表示可以输入任何字符
/// </summary>
[Description("小数部分的最大长度,如果小于 0,表示可以输入任何字符"), Browsable(true), DefaultValue(0)]
public int DotCount
{
get { return _dotCount; }
set
{
if (value < -1 || value > this.MaxLength)
throw new Exception("小数部分长度必须介于 -1 到 " + this.MaxLength.ToString() + " 之间。"); _dotCount = value;
if (!Validate(this.Text))
this.Text = "";
}
} /// 是否允许输入负数
/// <summary>
/// 是否允许输入负数
/// </summary>
[Description("是否允许输入负数"), Browsable(true), DefaultValue(false)]
public bool Positive
{
get { return _positive; }
set
{
_positive = value;
if (_positive)
_validStr = "0123456789-.";
else
_validStr = "0123456789.";
}
} /// 验证数据是否合法
/// <summary>
/// 验证数据是否合法
/// </summary>
/// <param name="str">要验证的字符串</param>
/// <returns></returns>
private bool Validate(string str)
{
//如果 _DotCount == -1,或字符串为空,不再验证,可以输入任何字符
if (_dotCount <= -1 || str == "")
return true; string str1 = this.Text.Substring(0, this.SelectionStart);
string str2 = this.Text.Substring(this.SelectionStart, this.Text.Length - this.SelectionLength - this.SelectionStart);
str = str1 + str + str2; //如果结果仅仅是“+”或“-”,允许输入
if (str == "+" || str == "-")
return true; //判断是否可以转换成数字
double doubleValue = 0;
if (!double.TryParse(str, out doubleValue))
return false; //如果小数位数为 0,表示只能输入整数
if (_dotCount == 0)
return str.IndexOf('.') < 0; //判断小数位数是否超过了指定的长度
int dotIndex = str.IndexOf('.');
if (dotIndex >= 0 && str.Length - dotIndex - 1 > _dotCount)
return false; return true;
} /// 重写 OnKeyDown 函数,处理按键
/// <summary>
/// 重写 OnKeyDown 函数,处理按键
/// </summary>
/// <param name="e"></param>
protected override void OnKeyDown(KeyEventArgs e)
{
_isValidChar = false; //系统默认快捷键的处理
if ((e.Control && e.KeyCode == Keys.C) //复制
|| (e.Control && e.KeyCode == Keys.Z) //撤销
|| (e.Control && e.KeyCode == Keys.V) //粘贴
|| (e.Control && e.KeyCode == Keys.X) //剪切
|| e.KeyCode == Keys.Back) //退格
_isValidChar = true;
else
_isValidChar = false; base.OnKeyDown(e);
} /// 重写的 OnkeyPress 函数,处理按键
/// <summary>
/// 重写的 OnkeyPress 函数,处理按键
/// </summary>
/// <param name="e"></param>
protected override void OnKeyPress(KeyPressEventArgs e)
{
if (!_isValidChar)
{
if (_dotCount > -1 && _validStr.IndexOf(e.KeyChar) < 0)
e.Handled = true;
else
e.Handled = !Validate(e.KeyChar.ToString());
} base.OnKeyPress(e);
} /// 重写粘贴消息,非法的字符不能粘贴
/// <summary>
/// 重写粘贴消息,非法的字符不能粘贴
/// </summary>
/// <param name="m"></param>
protected override void WndProc(ref Message m)
{
if (m.Msg == 0x0302)
{
string clipStr = Clipboard.GetText();
if(!Validate(clipStr))
return;
} base.WndProc(ref m);
} }