hello everyone,
i m trying to add row in database through this code:
PrivateSub btnadd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnadd.Click
Dim rowNew As System.Data.DataRow = DataSet31.Tables(0).NewRow
Dim temp As Random
rowNew.Item(4) = temp
Response.Write(rowNew.Item(4)) '**
DataSet31.Tables(0).Rows.Add(rowNew)
DataGrid1.EditItemIndex = DataGrid1.Items.Count
DataGrid1.DataSource = DataSet31
DataGrid1.DataBind()
End Sub
but when i click on add buton i get error that primary key cannot be null so i write ** line, but still getting error(i m using sql as database)
pl anyone help me..

Dani AI

Generated

The thread shows the problem was a schema/PK issue rather than the DataGrid itself — pointed this out and confirmed the database constraint was the root cause. Changing the database to allow NULLs will mask the symptom, but it is usually not the right fix for a primary key. Recommended approaches:

  • Let the database generate the key (SQL Server IDENTITY) and do not send a PK value from the client. After inserting, refresh the DataSet or use an InsertCommand that returns the identity so the client row gets the DB-assigned value (IDENTITY documentation).
  • If a client-side temporary key is needed before persisting, enable the DataColumn AutoIncrement on the DataTable (set seed/step appropriately). That produces unique temporary keys which are replaced when the DB returns the final key on update (DataColumn.AutoIncrement).
  • Always persist changes using a DataAdapter/InsertCommand and then reconcile the dataset with the database (for example, call Update and re-fill or retrieve the identity in the InsertCommand). This ensures client and server schemas remain consistent.

Troubleshooting checklist: verify the table schema and NOT NULL constraints, confirm the client actually assigns or generates a PK before adding the row, and ensure the DataTable schema (PrimaryKey and AllowDBNull) matches the database. Avoid making PKs nullable unless there is a deliberate, well-justified design reason.

Recommended Answers

All 2 Replies

I guess the error is from the sql database side. Set the column to accept nulls and try it out.

yeah i got the answer it was the error sql database thankyou for your answer

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.