TextBox条目基于SQL数据对象的验证

时间:2014-08-06 19:56:03

标签: c# sql winforms

我验证用户输入的文本,输入文本框,过滤掉非数字,然后比较> = /<从数据库中提取的对象。 我的问题发生在2个地方,虽然它可能只是1个问题。我将数据表项转换为字符串,然后转换为int。然后将此int传递给一系列if / else语句,这些语句应验证用户输入。单步执行程序后,我的转换语句似乎进行转换,然后继续跳过我的if / else语句。

   int classRPM;
        int fanRPM;
        string actualdata = string.Empty;
        char[] entereddata = txfanrpm.Text.ToCharArray();
        foreach (char aChar in entereddata.AsEnumerable())
        {
            if (Char.IsDigit(aChar))
            {
                actualdata = actualdata + aChar;

                using (Fanrpm ds = new Fanrpm(cbdesigntype.SelectedValue.ToString(), cbfansize.SelectedValue.ToString(), cbfanclass.SelectedValue.ToString()))
                {
                    DataTable dt = ds.dataset.Tables[0];
                    classRPM = Convert.ToInt32(dt.Rows[0].Field<string>("ClassRPM"));

                   // MessageBox.Show(aChar.ToString());
                    fanRPM = Convert.ToInt32(actualdata);
                    if (fanRPM >= classRPM)
                    {
                        MessageBox.Show("hi");
                    }
                    else if (fanRPM < classRPM)
                    {
                        MessageBox.Show("Hide");
                    }
                }
            }
            else
            {
                MessageBox.Show(aChar + " is not numeric");
                actualdata.Replace(aChar, ' ');
                actualdata.Trim();
            }
        }
        txfanrpm.Text = actualdata;

1 个答案:

答案 0 :(得分:1)

在上述评论之后,我认为您可以通过这种方式更改代码

// If the reading from the database gives always the same value is not correct to 
// exexute this code inside the foreach. Just do it one time here and go on....

float classRPM = 0.0f;
using (Fanrpm ds = new Fanrpm(cbdesigntype.SelectedValue.ToString(),
                              cbfansize.SelectedValue.ToString(), 
                              cbfanclass.SelectedValue.ToString()))
{
     DataTable dt = ds.dataset.Tables[0];
     classRPM = dt.Rows[0].Field<float>("ClassRPM");
}

float fanRPM;
string actualdata = string.Empty;

// No need to use AsEnumerable.... 
// And also this code could be easily replaced by single line float.TryParse 
// if you don't need to show a message box for every wrong char....
foreach (char aChar in txfanrpm.Text.ToCharArray())
{
    if (Char.IsDigit(aChar))
        actualdata = actualdata + aChar;
    else
        MessageBox.Show(aChar + " is not numeric");
}
// Now you could start your comparisons....
fanRPM = Convert.ToSingle(actualdata);
if (fanRPM >= classRPM)
   MessageBox.Show("hi");
else
   MessageBox.Show("Hide");