将 nvarchar 转换为 int 时 C# 转换失败

C# conversion failed when converting nvarchar to int

我正在尝试向我的数据库中插入值,但我一直收到错误

"conversion failed when converting the nvarchar 'Year' value to datatype int"

在 C# 中。我不知道如何解决这个问题。

这是我的代码:

private void btnSave_Click(object sender, EventArgs e)
{
    try
    {
        if (MessageBox.Show("Are you sure you want to save this book?", "Saving Record", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
        {
            //open connection to the database
            cn.Open();
            //command to be executed on the database
            cm = new SqlCommand("INSERT INTO Books(BookTitle, Edition, Genre, Author, Publisher, Year, ISBN) VALUES (@BookTitle, @Edition, @Genre, @Author, @Publisher, @Year, @ISBN )", cn);
            //set paramaters value
            cm.Parameters.AddWithValue("@booktitle", txtBook.Text);
            cm.Parameters.AddWithValue("@edition", txtEdition.Text);
            cm.Parameters.AddWithValue("@genre", txtGenre.Text);
            cm.Parameters.AddWithValue("@author", txtAuthor.Text);
            cm.Parameters.AddWithValue("@publisher", txtPublisher.Text);
            cm.Parameters.AddWithValue("@year", txtYear.Text);
            cm.Parameters.AddWithValue("@isbn", txtISBN.Text);
            //ask db to execute query
            cm.ExecuteNonQuery();
            //close connection
            cn.Close();
            MessageBox.Show("Record has been sucessfully saved!");
            Clear();
            frmlist.LoadRecords();
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

假设 table 中的年份字段是一个整数,您应该将一个整数变量绑定到它:

cm.Parameters.AddWithValue("@year", Int64.Parse(txtYear.Text));

你的Year是字符串类型,需要转成数字(int)。你可以使用像

这样的东西

cm.Parameters.AddWithValue("@year", int.Parse(txtYear.Text));

确保年份文本不为空且可转换为整数。

如果您像其他一些评论所建议的那样简单地添加 int.Parse(txtYear.Text),并且用户在 txtYear 字段中输入任何非数字字符,您将得到一个例外。

您应该将文本框更改为数字输入,这样该值就是一个整数,您就不必费心解析它并希望用户只输入数字,因为这将由数字输入本身强制执行。

查看这篇关于 Windows 表单中数字输入的文章: https://www.c-sharpcorner.com/blogs/how-to-create-a-textbox-accepting-only-numbers-in-windows-forms1

也就是说,如果您出于某种原因被迫使用文本输入:

我会尝试使用 int.TryParse(txtYear.Text, out int year)txtYear.Text 解析为整数,然后再将其传递给 SQL 命令。您可以在函数顶部执行类似以下操作来检查字段并在用户向字段中输入文本而不是所有数字时抛出更有意义的异常:

if(!int.TryParse(txtYear.Text, out int year))
{
  throw new Exception("Only digits are allowed in the year field");
}

//the rest of your code goes here
//and use the year variable for the @year parameter

先转换数值

String yr = txtYear.Text;
int yr = Convert.ToInt32(yr);

cm.Parameters.AddWithValue("@year",""+yr );