如何在条件C#中比较int.MaxValue

时间:2015-08-13 03:50:43

标签: c# asp.net

我希望在ASP.NET中绑定TextBox,其最大值可以是int.MaxValue。以下代码引发错误。

using (SqlConnection scon = new SqlConnection(cs))
{
    SqlCommand cmd = new SqlCommand("spDelete", scon);
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("@id", TextBox6.Text);
    scon.Open();
    if (TextBox6.Text != null && TextBox6.Text <= int.MaxValue)
    {
        int del = cmd.ExecuteNonQuery();
        if (del == 0)
        {
            Label2.Visible = true;
            Label2.ForeColor = System.Drawing.Color.Red;
            Label2.Text = TextBox6.Text + " Record not found";
        }
        else
        {
            Label2.Visible = true;
            Label2.ForeColor = System.Drawing.Color.Red;
            Label2.Text = TextBox6.Text + " Deleted Successfully";
            LoadGV();
        }
    }
    else
    {
        Label2.Visible = true;
        Label2.ForeColor = System.Drawing.Color.Red;
        Label2.Text = TextBox6.Text + " Enter a valid value";
    }
}

2 个答案:

答案 0 :(得分:6)

Textbox.Text是一个字符串,而不是int。我想你应该尝试将它转换为int之前:

int val;
if (Int32.TryParse(TextBox6.Text, out val) && val <= int.MaxValue) {
 // your stuff ...
}

请注意,您不需要在if块

之外设置连接

答案 1 :(得分:1)

Control.Text是字符串类型。您应该转换为int类型进行比较。

在行下面重复

if (TextBox6.Text != null && TextBox6.Text <= int.MaxValue)

bool validInput = false;
try {
    Int32.Parse(TextBox6.Text);
    validInput = true;
}
catch {
}
if (TextBox6.Text != null && validInput)

请注意,由于字符串输入无效,try可能会抛出异常。如果需要,您可以捕获特定的例外。您可以参考MSDN以获取可能的例外情况:https://msdn.microsoft.com/en-us/library/b3h1hf19(v=vs.110).aspx