how to set autoincremental Id in a table and add data

How to do it in Visual Studio? I've set Autoincrement = true in dataset design and set "YES" in identity specifications in database diagram. What else?

But how to add data now? When I'm trying to do like this but I've got an exception. The code.

 cmd = new SqlCommand("Insert into Subject" +
                " Values (namesubject,numberoflect,numberofpract)", conn);
            SqlParameter param = new SqlParameter();
            //param.ParameterName = "@idsubject";
            //param.Value = Convert.ToInt32(textBox1.Text);
            //param.SqlDbType = SqlDbType.Int;
            //cmd.Parameters.Add(param);
            //param = new SqlParameter();
            param.ParameterName = "namesubject";
            param.Value = textBox2.Text;
            param.SqlDbType = SqlDbType.Text;
            cmd.Parameters.Add(param);
            param = new SqlParameter();
            param.ParameterName = "numberoflect";
            if (textBox3.Text == "")
                textBox3.Text = "0";
            param.Value = Convert.ToInt32(textBox3.Text);
            param.SqlDbType = SqlDbType.Int;
            cmd.Parameters.Add(param);
            param = new SqlParameter();
            param.ParameterName = "numberofpract";
            if (textBox4.Text == "")
                textBox4.Text = "0";
            param.Value = Convert.ToInt32(textBox3.Text);
            param.SqlDbType = SqlDbType.Int;
            cmd.Parameters.Add(param);
            cmd.ExecuteNonQuery();

Autoincremental field - idsubject in this table.

Upvotes: 0

Views: 83

Answers (1)

dipak
dipak

Reputation: 2033

first of all Set Auto identity of idsubject to true

OR

 Create table ....
(
   idsubject int Auto identity (1,1) not null
   ....
   ....
)

and modify your insert code like

cmd = new SqlCommand("Insert into Subject(namesubject, numberoflect, numberofpract)" +
            " Values ('"+textBox2.Text+"',"+textBox3.Text+","+textBox3.Text+")", conn);

   cmd.ExecuteNonQuery();

Upvotes: 2

Related Questions