I want to know how to prevent duplicate entry to database table in case the table already have a record for that field.
As in my table column name: Website is unique column. And my uploading excel file may have same record with new data or maybe its complete duplicate so based on Column name Website i want to prevent entry of that duplicate entry and then enter another next record and this goes on.
I hope its clear, here is my code:
protected void btnSend_Click(object sender, EventArgs e)
{
//file upload path
string path = fileuploadExcel.PostedFile.FileName;
//Create connection string to Excel work book
string excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='C:\File.xlsx';Extended Properties=Excel 12.0;Persist Security Info=False";
//Create Connection to Excel work book
OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
//Create OleDbCommand to fetch data from Excel
OleDbCommand cmd = new OleDbCommand("Select * from [Sheet1$]", excelConnection);
excelConnection.Open();
OleDbDataReader dReader;
DataTable table = new DataTable();
dReader = cmd.ExecuteReader();
table.Load(dReader);
SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection);
//Give your Destination table name
sqlBulk.DestinationTableName = "TableName";
sqlBulk.WriteToServer(table);
excelConnection.Close();
int numberOfRowsInserted = table.Rows.Count;// <-- this is what was written.
string message = string.Format("<script>alert({0});</script>", numberOfRowsInserted);
ScriptManager.RegisterStartupScript(this, this.GetType(), "scr", message, false);
}