Click here to Skip to main content
13,141,354 members (86,464 online)
Rate this:
Please Sign up or sign in to vote.
See more:
i'm bigginer at c#.please somebody help me!
i want to put an id as a primary key in my database and fill it automatically but in c# there is an error with my code,how i can do that?
plz help me!
Posted 22-Sep-11 18:21pm
Rate this: bad
Please Sign up or sign in to vote.

Solution 1


In DataBase

On creation of table you specify Id as PrimaryKey and set Identity(1,1) then it takes care of filling in sequence[^]

On saving of entity you dont need to pass Id from application..

In c#

I dont think you need to do any thing...If you have a requirement in application to identify which property refers to PrimaryKey in datatable..then you can mark property is a Primary by means of Attribute..

more to know from[^]
Tech Code Freak 23-Sep-11 0:45am
Good links!
My 5up!
Rate this: bad
Please Sign up or sign in to vote.

Solution 2

You can make the primary key as Identity column. Itz possible via create table statement or GUI table designer.

CREATE TABLE myTableName ( myPrimary INT IDENTITY(1, 1), ... )

It automatically inserts the value for myPrimary key starting from 1 and increment of 1. You can change the start and increment points in IDENTITY(1, 1) parameters
Tech Code Freak 23-Sep-11 1:02am
Good Solution!
My 5up!
Rate this: bad
Please Sign up or sign in to vote.

Solution 3

DataTableName.PrimaryKey = new DataColumn() {DataTableName.Columns("ID")} u can set this way in C# Data table

as far database concern u add the the primay key in your Sql Table with this way


if you are creating new SQl Table

CREATE TABLE MyTable (cola INT IDENTITY(1, 1) PRIMARY KEY ,Col2 varchar)

IDENTITY always generates new Id at the time of insertion of any record

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy |
Web04 | 2.8.170915.1 | Last Updated 23 Sep 2011
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100