简体   繁体   中英

C# conversion failed when converting nvarchar to int

I am trying to insert values to my database but I keep getting the error

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

in c#. I don't know how to fix this.

Here is my code:

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);
    }
}

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

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

Your Year is a string type and needs to be converted to a number (int). You can use something like

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

Make sure that the year text is not empty and convertible to int.

Convert the value first

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

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

If you simply add int.Parse(txtYear.Text) as some of the other comments suggest, and the user enters any non-digit characters in the txtYear field you are going to get an exception.

You ought to change your text box to a number input so the value is an integer and you won't have to bother parsing it and hoping users input numbers only because that will be enforced by the number input itself.

Checkout this article on numeric inputs in Windows Forms: https://www.c-sharpcorner.com/blogs/how-to-create-a-textbox-accepting-only-numbers-in-windows-forms1

That being said, if you are being forced to use a text input for some reason:

I would try and parse txtYear.Text as an integer using int.TryParse(txtYear.Text, out int year) before passing it into the SQL command. You can do something like the following at the top of the function to check the field and throw a more meaningful exception if the user has entered text into the field instead of all numbers:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM