CONVERSION FAILED WHEN CONVERTING THE NVARCHAR VALUE 'MEETINGID' TO DATA TYPE INT

Hugh Jackman

Total Post:52

Points:366
Posted by  Hugh Jackman
C# 
 1300  View(s)
Ratings:
Rate this:

I have a dropdownlist and I am trying to insert the DataValueField into a database table. The DataValueField is retrieved from the database and the data type for the column is INT. However, when the run the query I get this error message

 

Conversion failed when converting the nvarchar value 'meetingId' to data type int.

Code:

 

if (MinuteUpload.HasFile)

{

    string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

 

    string updateSql = "UPDATE Project_Meeting SET meetingMinute = @meetingMinute WHERE meetingId = @MeetingId"; ;

 

    using (SqlConnection myConnection = new SqlConnection(connectionString))

    {

        myConnection.Open();

 

        SqlCommand myCommand = new SqlCommand(updateSql, myConnection);

 

        myCommand.Parameters.AddWithValue("@meetingMinute", "postUpload/" + filename);

        myCommand.Parameters.AddWithValue("@MeetingId", MinuteDropDown.DataValueField);

 

        myCommand.ExecuteNonQuery();

 

        myConnection.Close();

    }

}

However, when I try

 

Convert.ToIint.TryParse16(MinuteDropDown.DataValueField.Trim())

I get this error:

 

Input string was not in a correct format.

  1. Elena Glibart

    Post:42

    Points:296
    Re: Conversion failed when converting the nvarchar value 'meetingId' to data type int

    myCommand.Parameters.AddWithValue("@MeetingId", MinuteDropDown.DataValueField);

    There are two things wrong. First, DataValueField represents the name of the property, not the value of the property. SelectedValue is what you want.

     

    But once you make that change, SelectedValue is still a string. You should parse that into an int in advance, before adding your parameter:

     

    int meetingId = int.Parse(MinuteDropDown.SelectedValue);

    myCommand.Parameters.AddWithValue("@MeetingId", meetingId);

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!