insertexecutenonquery

can't insert data into SQL Server with C#


I'm trying to insert data to data base, first i used tray catch and debugging. there was no error but data didn't insert. then i remove try catch and find this:

"Cannot insert the value NULL into column 'ContactID', table 'Contact_DB3.dbo.TContacts'; column does not allow nulls."

My inputs isn't null how can i fix this?

Screenshot

public bool Insert(string name, string family, string mobile)
        {
            SqlConnection connection = new SqlConnection(connectionstring);
            string query = "insert into TContacts (Name,Family,Mobile) Values ( @Name , @Family , @Mobile ) ";
            SqlCommand command = new SqlCommand(query, connection);
            command.Parameters.AddWithValue("@Name", name);
            command.Parameters.AddWithValue("@Family", family);
            command.Parameters.AddWithValue("@Mobile", mobile);
            connection.Open();
            command.ExecuteNonQuery();
            return true;
            connection.Close();
            
        }

Solution

  • If your table does not allow null as per your question the column is ContactID. You cna do one of 2 things.

    1. From your code generate an ID using GUID and pass it to the save call. OR
    2. Set the ContactID in the table to an identity column type