Click here to Skip to main content
15,906,285 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
error:

C#
Exception thrown: 'System.Data.SqlClient.SqlException' in System.Data.dll

Additional information: Cannot insert the value NULL into column 'Id', table 'Login.dbo.Rota'; column does not allow nulls. INSERT fails.

The statement has been terminated.


its basically adding a blank data(NULL) to my database when it shouldn't be... i think

form pic: http://postimg.org/image/skqp12obj/[^]

my code:
C#
        private void button2_Click(object sender, EventArgs e)
        {
            const string con = "Data Source = dqq5ndqef2.database.windows.net; Initial Catalog = Login; Integrated Security = False; User ID = richardjacobs97; Password = ********; Connect Timeout = 15; Encrypt = False; TrustServerCertificate = False; ApplicationIntent = ReadWrite; MultiSubnetFailover = False";

            using (SqlConnection connection = new SqlConnection(con))
            {
                connection.Open();

                using (SqlTransaction transaction = connection.BeginTransaction())
                using (SqlCommand cmd = new SqlCommand("INSERT INTO Rota (Id, Name, DateWorking) Values (@Id, @Name, @DateWorking)", connection, transaction))
                {
                    cmd.CommandType = CommandType.Text;

                    for (int i = 0; i < dataGridView1.Rows.Count; i++)
                    {
                        cmd.Parameters.Clear();

                            cmd.Parameters.AddWithValue("@Id", dataGridView1.Rows[i].Cells["Id"].Value);
                            cmd.Parameters.AddWithValue("@Name", dataGridView1.Rows[i].Cells["Name"].Value);
                            cmd.Parameters.AddWithValue("@DateWorking", dataGridView1.Rows[i].Cells["DateWorking"].Value);

                        cmd.ExecuteNonQuery();
                    }
                    transaction.Commit();
                }

                using (SqlCommand cmd = new SqlCommand("SELECT Id, Name, DateWorking FROM Rota", connection))
                {
                    DataTable dt = new DataTable();
                    SqlDataAdapter sda = new SqlDataAdapter(cmd);
                    sda.Fill(dt);
                    dataGridView1.DataSource = dt;
                }
            }
        }
    }
}


any sugguestions?
Posted
Updated 28-Feb-18 0:49am
v2

1 solution

Put a breakpoint in the following line and check the value of @Id
C#
cmd.Parameters.AddWithValue("@Id", dataGridView1.Rows[i].Cells["Id"].Value);

Probably Id is the primary key for the table and should be autogenerated.
Doing following should resolve your problem in this case
Auto increment primary key in SQL Server[^]

Hope, it helps :)
 
Share this answer
 

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