Click here to Skip to main content
15,886,919 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm trying to work with uploading excel in asp.net c# web form and save in sql however it also upload duplicate data in row.

C#
private bool uploadfile1()
{
	try
	{
		if (FileUpload1.PostedFile.FileName != "" || FileUpload1.PostedFile.FileName != "File Template")
		{
			this.checkDirectory();
			FileUpload1.PostedFile.SaveAs(Server.MapPath("") + "\\Uploads\\" + FileUpload1.FileName);
			filename = FileUpload1.FileName;
			path = Server.MapPath("") + "\\Uploads\\";
			ExcelCS xl = new ExcelCS();
			xl.UserId = (Session["userid"] != null) ? Session["userid"].ToString() : String.Empty;
			xl.Session = (Session["sessionID"] != null) ? Session["sessionID"].ToString() : String.Empty;
			if (xl.ParseExcelFile(path + filename, true, 1))
			{
				listdata save = new listdata();
				if (save.save())
				{
					Class.JSclass.ShowAlert(save.RecordsUploaded.ToString() + " item(s) uploaded and " + save.TotalUpdated.ToString() + " item(s) updated out of " + save.TotalRecords.ToString() + " Record(s).");
					listweb.Class.Logger.writeLog(Session["userid"].ToString(), Session["sessionID"].ToString(), "frmUploadFile.uploadfile1", "File uploaded successfully!", "", "", Class.LogCategories.SELECT);
					Class.JSclass.refreshMainPage();
					return true;
				}
			}
			else
			{
				Class.JSclass.ShowAlert("Invalid file format please use specified template.");
				listweb.Class.Logger.writeLog(Session["userid"].ToString(), Session["sessionID"].ToString(), "frmUploadFile.uploadfile1.ParseExcelFile", "Error: " + xl.Message, "", "", Class.LogCategories.SELECT);
				return false;
			}
		}
	}
	catch (Exception e)
	{
		Class.JSclass.ShowAlert("Error: " + e.Message);
		listweb.Class.Logger.writeLog(Session["userid"].ToString(), Session["sessionID"].ToString(), "frmUploadFile.uploadfile1", "Error: " + e.Message, "", "", Class.LogCategories.SELECT);
	}

	Class.JSclass.ShowAlert("File upload failed!");
	return false;
}


What I have tried:

I tried only tried to save the upload in sql however with duplicate/ same data in upload/save in sql. I wanted to void the duplication of the data
Posted
Updated 28-Apr-23 2:46am
v2

1 solution

Two ways to avoid duplicates:
1) Check first to see if the row exists, and if it does, don't INSERT
2) Try to do an UPDATE and see if the "rows affected" count is zero. If it is, there was no such row and it's safe to INSERT. If it is non-zero, the new value has overwritten the old.
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900