The program i got is able to load CSV and Excel files in to a datagridview. This works perfectly fine except the CSV files retain old data.
For example, the CSV file has 30 values. i load the data in to the datagridview and it works fine. I close the application and i then edit the CSV file removing 26 of the rows. The next time i open the application and load the file it still get's the version with 30 values even tho that file no longer exists.
To be clear, i open and edit the file in Notepad and it works as intended, but even after editing it in notepad my Winform application seems to load the previous version. Even if i rename the file it still takes the data that should no longer exist. Even after completely restarting the PC the file still retains data that should not exist. BUT! If i move the file to a different folder (add new folder and just throw it in there) it does load the new data...
EDIT: It seems that it is actually loading all CSV files in the folder. (including older versions)
what could cause this problem? Seeing the Excel files are not experiencing this problem.
The code used:
private void OpenExcel()
{
OpenFileDialog openFileDialog1 = new OpenFileDialog
{
InitialDirectory = @"C:\",
Title = "Browse Text Files",
CheckFileExists = true,
CheckPathExists = true,
DefaultExt = "txt",
FilterIndex = 2,
RestoreDirectory = true,
ReadOnlyChecked = true,
ShowReadOnly = true,
Filter = "Excel Worksheets|*.csv"
};
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
FileLocation = openFileDialog1.FileName;
GetExcelSheetNames(openFileDialog1.FileName);
MyConnection = new OleDbConnection(connString);
MyCommand = new OleDbDataAdapter("select * from [" + SheetName + "]", MyConnection);
MyCommand.TableMappings.Add("Table", "TestTable");
Datatable_Temp = new DataTable();
MyCommand.Fill(Datatable_Temp);
MyConnection.Close();
}
else
{
Canceled = true;
}
}
private string GetExcelSheetNames(string excelFile)
{
OleDbConnection objConn = null;
DataTable dt = null;
string CSVOrNot = excelFile.Substring(excelFile.Length - 3);
try
{
// Connection String.
if (CSVOrNot == "csv")
{
connString = string.Format(@"Provider=Microsoft.Jet.OleDb.4.0; Data Source={0};Extended Properties=""Text;HDR=YES;FMT=Delimited""", Path.GetDirectoryName(excelFile));
}
else
{
connString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + excelFile + ";Extended Properties=Excel 12.0;";
}
// Create connection object by using the preceding connection string.
objConn = new OleDbConnection(connString);
// Open connection with the database.
objConn.Open();
// Get the data table containg the schema guid.
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
MessageBox.Show("No Data Found");
return null;
}
SheetName = dt.Rows[0]["TABLE_NAME"].ToString();
return SheetName;
}
catch
{
return null;
}
finally
{
// Clean up.
if (objConn != null)
{
objConn.Close();
objConn.Dispose();
}
if (dt != null)
{
dt.Dispose();
}
}
}