C# .NET - check unique value before adding to DataTable

Asked By Sharad Chandra on 12-Aug-11 06:15 AM
Hi friends
i have one datatable and i want i must contain unique value, i set:
dt.Columns[0].Unique = true;

now  value added on datatable form textbox, i want to prevent add duplicate value in datatable without loop,
so that unique value must be added in datatable
how can i do it, help me
Thanks
Jitendra Faye replied to Sharad Chandra on 12-Aug-11 06:21 AM
For this use this code-

string s = "primaryKeyValue";

DataRow foundRow = dataSet1.Tables["AnyTable"].Rows.Find(s); if (foundRow != null) { MessageBox.Show("Already Exist")); } else { //Add Value to DataTable
}

Try this code and let me know,
Riley K replied to Sharad Chandra on 12-Aug-11 06:28 AM

Try this way

DataRow[] dupRows =  myDataTable.Select("columnName1 like '%" + TextBox.Text + "%'");

If(dupRows!=null)
 {
   MessageBox.Show("This record is already present.")
 }

Regards
Anoop S replied to Sharad Chandra on 12-Aug-11 06:30 AM
Use UNIQUE Constraint for table

The UNIQUE constraint uniquely identifies each record in a database table.

The UNIQUE and PRIMARY KEY constraints both provide a guarantee for uniqueness for a column or set of columns.

CREATE TABLE Persons
(
P_Id int NOT NULL UNIQUE,
LastName varchar(255) NOT NULL,
-----
-----
}
Web Star replied to Sharad Chandra on 12-Aug-11 06:53 AM
For Inserting unique value in database table, you are trying to get unique value in DataTable this approch is wrong, because if you check uniqueness in datatable and insert into database table but when next time same datatable contain unique rows but that row may be exists in table and when you insert it will be duplicate so I suggest you don't try this approach.

Better is you check uniqueness just before the insert row in database table, so you check exists of that column value in database table if not exist than only insert.
eg.


CREATE PROC SPNAME
(
@USERNAME VARCHAR(50)
)
AS
BEGIN
IF NOT EXISTS(SELECT * FROM TblName WHERE USERNAME = @USERNAME)
BEGIN
INSERT INTO TblName VALUES(@USERNAME)
END
ELSE
BEGIN
-- RETURN MESSAGE HERE FOR EXIST THAT RECORD OR WHAT YOU WANT
END
END
aneesa replied to Sharad Chandra on 12-Aug-11 07:14 AM



Datarow[] dr=Dt.Select("column="+textbox1.text);
if(dr.Length==0)// this means datatable doesnt contain that value
{
/// add the code to insert data
}
Sharad Chandra replied to Jitendra Faye on 12-Aug-11 07:32 AM
HI Vickey
this is working for my requirement, Thank u mery much
Jitendra Faye replied to Sharad Chandra on 12-Aug-11 08:31 AM
You always welcome.