how to handle exception when a field in database does not allow nulls

时间:2016-10-20 13:13:32

标签: c# sql exception

I have a field in the database that is nvarchar and it cannot be null. I am having a problem to display the specific message when an error occurs. When inserting in my database,I tried two things. first:

if (string.IsNullOrWhiteSpace(textBoxCity.Text))
    MessageBox.Show("This cannot be empty");
else  
    cmd.Parameters.Add("@city", SqlDbType.NVarChar).Value = textBoxCity.Text;

second:

try
{
    if(string.IsNullOrWhiteSpace(textBoxCity.Text))
    {
        MessageBox.Show("Cannot be empty");

    }
    else
    {
        cmd.Parameters.Add("@city", SqlDbType.NVarChar).Value = textBoxCity.Text;
    }
}
catch (Exception ex)
{
    if (ex is FormatException)
    {
        MessageBox.Show("Cannot be empty");
        return;
    }
    else if (ex is SqlException)
    {
        MessageBox.Show("Cannot be empty");
    }
    throw;
}

the second one gives me the right message but it also gives me an exception where it says the scalar must be declared.how can I handle that? I've tried to give it a db.null,but because a field does not allow nulls,the it gives me another exception,again that is not format,or sql.Can you tell me what kind of exception is this,or how can I handle this?

EDIT: At first I had a mistake,where it was supposed to be nvarchar sqldbtype,there was int.

2 个答案:

答案 0 :(得分:1)

cmd.Parameters.Add("@city", SqlDbType.Int).Value = textBoxCity.Text;

You defined your parameter to be of type int and you are giving it string. You need to parse the value from the TextBox to int.

int city = 0;
int.TryParse(textBoxCity.Text, out city)
cmd.Parameters.Add("@city", SqlDbType.Int).Value = city;

答案 1 :(得分:1)

如果值是必需的但未提供,则不应尝试将其插入数据库 - 当然这会导致异常。

bool valid = true;
if (string.IsNullOrWhiteSpace(textBoxCity.Text))
{
     valid = false;
     MessageBox.Show("This cannot be empty");
}

if(valid)
{
    cmd.Parameters.Add("@city", SqlDbType.Int).Value = textBoxCity.Text;
    //execute sql query here
}

正如另一个答案所说,你也应该将文本解析成一个int。

相关问题