Adding a Primary Key to a DataTable

by Jagadish Pulakhandam on 9/1/2011 12:44:59 PM
Rated 0 from 0 votes
Brief: Demonstrates on adding a Primary Key constraint to a DataTable in ADO.NET
Posted to: Storing data offline (Disconnected) using ADO.NET
Add to DiggAdd to del.icio.usAdd to FURLAdd to RedditAdd to YahooAdd to BlinklistAdd to GoogleAdd to ma.gnoliaAdd to ShadowsAdd to Technorati

It is relatively straight forward.  You need to enable "PrimaryKey" property of DataTable to true.

Screen shot:




Source Code:

01.using System;
02.using System.Collections.Generic;
03.using System.ComponentModel;
04.using System.Data;
05.using System.Drawing;
06.using System.Linq;
07.using System.Text;
08.using System.Windows.Forms;
09. 
10.namespace CSPrimaryKeyConstraint
11.{
12.    public partial class Form1 : Form
13.    {
14.        DataTable dt;
15. 
16.        public Form1()
17.        {
18.            InitializeComponent();
19.        }
20. 
21.        private void Form1_Load(object sender, EventArgs e)
22.        {
23.            dt = new DataTable();
24. 
25.            DataColumn dcRegdno = new DataColumn();
26.            dcRegdno.ColumnName = "Regdno";
27.            dcRegdno.DataType = typeof(System.Int32);
28.            dt.Columns.Add(dcRegdno);
29. 
30.            DataColumn dcName = new DataColumn();
31.            dcName.ColumnName = "Name";
32.            dcName.DataType = typeof(System.String);
33.            dt.Columns.Add(dcName);
34. 
35.            dt.PrimaryKey = new DataColumn[] { dcRegdno };
36. 
37.            this.DataGridView1.DataSource = dt;
38. 
39.        }
40. 
41.        private void btnAdd_Click(object sender, EventArgs e)
42.        {
43.            try
44.            {
45.                dt.Rows.Add(this.txtRegdno.Text, this.txtName.Text);
46.            }
47.            catch (Exception ex)
48.            {
49.                MessageBox.Show(ex.Message);
50.            }
51.        }
52.    }
53.}

Join the .NET Code Central Community and join the discussion!
Signing-up is FREE and quick. Do it now, we want to hear your opinion
0

Rated 0 from 0 votes ( login  to rate)
DotnetKicks DotnetKicksDe DotNetShoutout

Attachments / Source Code
You need to Login or Join for FREE to download the following