Below is my code:
protected void SubmitCSV_Click(object sender, ImageClickEventArgs e)
{ //Check Routes File Uploader for file
if (ImportCSV.HasFile)
{
//Get File name
string fileName = ImportCSV.FileName;
//Read CSV
StreamReader ReadUploadedFile = new StreamReader(ImportCSV.FileContent);
//Parse CSV
var pathOfCSVFile = ReadUploadedFile;
//Gather CSV contents
var adapter = new GenericParsing.GenericParserAdapter(pathOfCSVFile);
//Ignore first row
adapter.FirstRowHasHeader = true;
DataTable TempRouteDataTable = adapter.GetDataTable();
if (ExcelDDL.SelectedValue == "Active Service Keys" && fileName == "ActiveServiceKeys.csv")
{
SEPTA_DS.ActiveServiceKeysTBLDataTable GetActiveServiceKeys = (SEPTA_DS.ActiveServiceKeysTBLDataTable)askta.GetData();
var hasData = GetActiveServiceKeys.Rows.Count > 0;
//Loop through each row and insert into database
foreach (DataRow row in TempRouteDataTable.Rows)
{
//Gather column headers
var category = Convert.ToString(CategoryDDL.SelectedItem);
var agency = Convert.ToString(row["Agency"]);
var route = Convert.ToString(row["Route"]);
var direction = Convert.ToString(row["Direction"]);
var serviceKey = Convert.ToString(row["Service Key"]);
var language = Convert.ToString(row["Language"]);
var activeServiceKeys = Convert.ToString(row["Active Service Keys"]);
//Check if data already exists
if (hasData == true)
{
var originalID = Convert.ToInt32(GetActiveServiceKeys.Rows[0] ["ActiveServiceKeysID"]);
int updateData = Convert.ToInt32(askta.UpdateActiveServiceKeys(category, agency, route, direction, serviceKey, language, activeServiceKeys, originalID));
}
else
{
int insertData = Convert.ToInt32(askta.InsertActiveServiceKeys(category, agency, route, direction, serviceKey, language, activeServiceKeys));
}
}
}
}
}
The problem arises after rows exist. The foreach
is currently reading a CSV uploaded so eahc time the foreach
is fired it places a row into the database.
EDIT:
When data DOES NOT exist in the database I want to run the insert
method.
When it DOES exist I want to run the update
method.
PROBLEM: When running an update
method you require the originalID
(auto-incrementing int). Since each row from the uploading CSV is within a foreach
I am unfamiliar on how to grab the originalID
per loop.
Currently, (just fixed) I had a 0 but that will not change per loop.