Home > other >  Problem with database connection C# from System.Data.SqlClient
Problem with database connection C# from System.Data.SqlClient

Time:05-20

I have looked at all the similar questions on this topic but none seem to work for me.

When I try to run my application, I get the following error:

System.Data.SqlClient.SqlException: 'Cannot insert the value NULL into column 'Id', table 'C:\FINALLY\DATABASE.MDF.dbo.loginTB'; column does not allow nulls. INSERT fails.

Here is my code:

private void btnContinued_reg_Click(object sender, EventArgs e)
{
    SqlConnection cn = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\finally\DataBase.mdf;Integrated Security=True;Connect Timeout=30");

    SqlCommand cmd= new SqlCommand("insert into loginTB(username,password)values('"   txtUserName_reg.Text   "','"   txtPaswword_reg.Text   "')",cn);

    cn.Open();
    cmd.ExecuteNonQuery();
    cn.Close();

    MessageBox.Show("good");
}

What am I doing wrong?

A snapshot of my code:

enter image description here

CodePudding user response:

The problem does not indicate a connection problem at all. It seems that you are trying to insert a record into a table, and you are trying to pass null as the id, which gives you the error.

My guess would be the error is in the definition of that table loginTB, you make sure the column id has the property IDENTITY, since you are using SQL Server.

An example would be like this:

CREATE TABLE new_employees  
(  
    id_num int PRIMARY KEY IDENTITY(1,1),  
    fname varchar (20),  
    minit char(1),  
    lname varchar(30)  
); 

Identity columns can be used for generating key values. The identity property on a column guarantees the following:

  • Each new value is generated based on the current seed & increment.
  • Each new value for a particular transaction is different from other concurrent transactions on the table.

The identity property on a column does not guarantee the following:

  • Uniqueness of the value
  • Uniqueness must be enforced by using a PRIMARY KEY or UNIQUE constraint or UNIQUE index.

CodePudding user response:

Follow up answer of previous answers.

If you already created a table and want to modify it to work correctly:

Screenshot

Go to the table properties from SSMS tool and select the identity column and save the properties. Identity column must be marked as not nullable.

  • Related