0

I need to upload data from excel sheet to my grid view. but I need to prevent insertion of duplicate rows. so how can I do this with my dataset ? how do I check the dataset if it contains duplicates. if it has duplicates, I need to give an error message. here is my code.

odfExcelGet.Title = "Excel Upload";

odfExcelGet.FileName = "Excel";
odfExcelGet.Filter = "Excel File (*.xls;*.xlsx;)|*.xls;*.xlsx;";
odfExcelGet.InitialDirectory = @"c:\";
odfExcelGet.ShowDialog();
txtAddress.Text = odfExcelGet.FileName;

this.Cursor = Cursors.WaitCursor; 

string ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=";
ConnectionString += odfExcelGet.FileName;
ConnectionString += @";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1"";";

OleDbDataAdapter da = new OleDbDataAdapter("select * from [Sheet1$]", ConnectionString);
da.Fill(dsMain);

dgGrid.DataSource = dsMain.Tables[0];

how do I modify this code to prevent duplication.

M.kazem Akhgary
  • 18,645
  • 8
  • 57
  • 118
Didu
  • 79
  • 2
  • 11
  • I referred above link. but is there any other way to do this? I mean without using hash table? – Didu Oct 31 '17 at 03:53
  • Instead of `select * from [Sheet1$]`, try `select distinct * from [Sheet1$]` - that might work. But it depends on your definition of unique – Nick.Mc Oct 31 '17 at 05:08
  • thanks Nick. but the requirement of mine is differ from this solution. – Didu Oct 31 '17 at 10:55
  • @Didu Please check my answer below and let me know whether it is working or not. If yes please accept the answer. – Ravi Kumar G N Nov 10 '17 at 04:56

1 Answers1

0

A Simple way would be, Replace ColumnType with Type of your column which is unique.

var newDataTable = dsMain.Tables[0];
dgGrid.DataSource = newDataTable.AsEnumerable().GroupBy(col => col.Field<ColumnType>("ColumnName"))
.Select(x=>x.First()).CopyToDataTable();
Ravi Kumar G N
  • 396
  • 1
  • 3
  • 11