从文本框中获取数据时捕获异常

时间:2013-11-10 12:16:20

标签: c# try-catch

用户需要在文本框中插入一些数字,用','分隔。现在,如果他做错了什么我想抛出异常(例如,如果他写了1; 2,3)。

string perm = this.tbxPerm.Text;
string[] elPerm = this.perm.Split(',');

请在这里建议我如何使用try catch块。

3 个答案:

答案 0 :(得分:2)

当您点击不良数据时,您可以只验证它并在不符合您的标准时拒绝它,而不是抛出异常。考虑以下函数来检测字符串中的无效字符。

    public bool CheckString(string str)
    {
            char[] badChars = new char[] { '#', '$', '!', '@', '%', '_', ';' }; 

            foreach (char bad in badChars)
            {
                if (str.Contains(bad))
                    return false;
            }

            return true;
    }

用法可能类似于:

        string perm = this.tbxPerm.Text

           if (!CheckString(perm))
           { 
           System.Windows.Forms.MessageBox.Show(perm + " is invalid, please try again");
           }

答案 1 :(得分:1)

使用linq:

string perm = this.tbxPerm.Text;

if(perm.Any(c=> !char.IsDigit(c) && c != ','))
   throw new Exception("Wrong input");

答案 2 :(得分:1)

您可以使用TryParse()功能检查转换是否有效 如果转换成功,TryParse()函数将返回true,否则返回false

            string perm = this.tbxPerm.Text;
            string[] elPerm = perm.Split(',');
            int num;
            for (int i = 0; i < elPerm.Length; i++)
            {
                if(!int.TryParse(elPerm[i],out num))
                throw new Exception("Invalid Data Found");
            }