'ASP.NET C# Web Form
This is the error Exception Details: System.InvalidCastException: Object must implement IConvertible.
This is the code that I have, and I am tryin to solve this error for about 5 hours. I don't know if it's something about the type of the values.
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection sqlConnection = new SqlConnection(SqlDataSourceAutovehicule.ConnectionString);
sqlConnection.Open();
SqlCommand sqlCommand = new SqlCommand("INSERT INTO Autovehicul(Marca, Model, Stoc, Categorie) VALUES (" +
"@marca, @model, @stoc, @categorie)", sqlConnection);
SqlParameter pMarca = new SqlParameter("@marca", SqlDbType.VarChar, 50);
pMarca.Value = txtMarca.Text;
SqlParameter pModel = new SqlParameter("@model", SqlDbType.VarChar, 50);
pModel.Value = txtModel.Text;
SqlParameter pStoc = new SqlParameter("@stoc", SqlDbType.Int, 50);
pStoc.Value = txtStoc.Text;
SqlParameter pCategorie = new SqlParameter("@categorie", SqlDbType.Int, 50);
pCategorie.Value = DropDownList1.SelectedValue;
sqlCommand.Parameters.Add(pMarca);
sqlCommand.Parameters.Add(pModel);
sqlCommand.Parameters.Add(pStoc);
sqlCommand.Parameters.Add(pCategorie);
if (sqlCommand.ExecuteNonQuery() > 0)
{
Label1.Text = "adaugare reusita";
GridView1.DataBind();
}
else
{
Label1.Text = "adaugare nereusita";
}
}
Solution 1:[1]
A few things?
You don't have 50 digit long integer, so you can dump the optional ,50) for those parmamters.
Also, it looks like your combo box if not selected, is probably returning a "" (empty string). While that can be shoved into a paramter, when it evaluates, it can't convert to a 0.
So, I suggest this:
SqlParameter pCategorie = new SqlParameter("@categorie", SqlDbType.Int);
if (DropDownList1.SelectedValue == "")
pCategorie.Value = 0;
else
pCategorie.Value = DropDownList1SelectedValue;
So, you might want to check tht combo box for null, or a "", but that conversion is failing. And you not see the fail until the execute command.
And the same goes for your text boxes - if they ahve "" (no value, then you need to pass zero.
So, say like this:
using (SqlConnection conn = new SqlConnection(""))
{
using (SqlCommand cmdSQL = new SqlCommand(
"INSERT INTO Autovehicul (Marca, Model, Stoc, Categorie) " +
"VALUES (@marca, @model, @stoc, @categorie", conn))
{
conn.Open();
cmdSQL.Parameters.Add("@marca", SqlDbType.VarChar).Value = txtMarca.Text;
cmdSQL.Parameters.Add("@model", SqlDbType.VarChar).Value = txtModel.Text;
if (if txtSToc.Text == "")
txtStoc.Text = 0;
cmdSQL.Parameters.Add("@stoc", SqlDbType.Int, 50).Value = txtStoc.Text;
if (DropDrownList1.SelectedValue == "")
cmdSQL.Parameters.Add("@categorie", SqlDbType.Int).Value = 0;
else
cmdSQL.Parameters.Add("@categorie", SqlDbType.Int).Value = DropDownList1.SelectedValue;
if (cmdSQL.ExecuteNonQuery() > 0)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Albert D. Kallal |