Click here to Skip to main content
15,891,033 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
error:Specified cast is not valid


this is my code.........

C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace saving_data_backend
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection();
            con.ConnectionString = "Data Source=CIODEV03\\SQLEXPRESS;
            Initial Catalog=EmployeeDB;
            Integrated Security=True";
            try
            {
                //create  a sql command to get a unique contactID.

                SqlCommand cmd = new SqlCommand("Select MAX(cemployeeCode) from 
                                                               employee2", con);
                // Open the database connection
                con.Open();

                //Execuete the sql command 
                int intNextID = (int)cmd.ExecuteScalar() + 1;

                //Create a command to add a new row...

                SqlCommand cmd1 = new SqlCommand(String.Format("Insert into 
                        employee2 (cemployeeCode,Name,Age) values
                      ({0},'{1}','{2}')", intNextID, textBox1.Text,
                       textBox2.Text), con);

                //Execute the command 
                if (cmd1.ExecuteNonQuery() > 0)
                {
                    label1.Text = "Record Added";
                    textBox1.Text = "";
                    textBox2.Text = "";
                }
                else
                {
                    label1.Text = "Couldn't add record";
                }
            }
            catch (Exception ex)
            {
                label1.Text = "Error:" + ex.Message;
            }
            finally
            {
                //close the con.
                con.Close();
            }
        }
    }
}




and my database is.......

SQL
cempcode(PK,int NOT NULL)
Name (nvarchar(50) NULL)
Age (nvarchar(50) NULL)
Posted
Updated 9-Feb-12 21:14pm
v2
Comments
walterhevedeich 10-Feb-12 3:31am    
Have you just mistyped cempcode instead of cemployeeCode?
manognya kota 10-Feb-12 3:33am    
Did u put a breakpoint and check where exactly is the error occuring?

1 solution

Don't do it like that!
Do not concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Use Parametrized queries instead.

SQL
SqlCommand cmd1 = new SqlCommand(String.Format("Insert into employee2 (cemployeeCode,Name,Age) values
                      (@ID, @NAME, @AGE"), con);
cmd1.Parameters.AddWithValue("@ID", intNextID);
cmd1.Parameters.AddWithValue("@NAME", textBox1.Text);
cmd1.Parameters.AddWithValue("@AGE", textBox2.Text);

That may fix your problem.

But what you are doing there is very, very dangerous.
The only reason for using SQL is to work in a multiuser environment.
What happens if two users try to add a record at the same time? They will both try to insert the same ID!

Either use an Identity spec in your ID column (and let the DB handle assigning a value), or use a Guid instead - there are other ways but those are the easiest.
 
Share this answer
 
Comments
rockpune 10-Feb-12 3:51am    
thank u sir

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900