example csv data:
Code
datetime Miliseconds MachineAutoStartStop Pressure
25/10/2022 0:00 655 1 0.382796
25/10/2022 0:00 899 1 0.382796
25/10/2022 10:31 37 1 0.382796
25/10/2022 10:31 38 1 0.382796
25/10/2022 10:31 787 1 0.382796error:error:System.InvalidCastException: 'Specified cast is not valid.'
Code
C#
private void btnbrowse_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.DefaultExt = ".csv";
ofd.Filter = "Comma Separated (*.csv)|*.csv";
ofd.ShowDialog();
txtfilename.Text = ofd.FileName;
DataTable dt = new DataTable();
dataGridView1.DataSource = dt.DefaultView;
{
}
}
private void btnclose_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnimport_Click(object sender, EventArgs e)
{
Cursor = Cursors.WaitCursor;
DataTable dt = GetDataFromFile();
if (dt == null) return;
SaveImportDataToDatabase(dt);
MessageBox.Show("Data Import success!");
txtfilename.Text = string.Empty;
Cursor = Cursors.Default;
}
private DataTable GetDataFromFile()
{
DataTable dt = new DataTable();
try
{
using (StreamReader sr = new StreamReader(txtfilename.Text))
{
string header = sr.ReadLine();
if (string.IsNullOrEmpty(header))
{
MessageBox.Show("no file data");
return null;
}
string[] headerColumns = header.Split(',');
foreach (string headerColumn in headerColumns)
{
dt.Columns.Add(headerColumn);
}
while (!sr.EndOfStream)
{
string line = sr.ReadLine();
if (string.IsNullOrEmpty(line)) continue;
string[] fields = line.Split(',');
DataRow importedRow = dt.NewRow();
for (int i = 0; i < fields.Count(); i++)
{
importedRow[i] = fields[i];
}
dt.Rows.Add(importedRow);
}
}
}
catch (Exception e)
{
Console.WriteLine("the file could not be read:");
Console.WriteLine(e.Message);
}
return dt;
}
private void SaveImportDataToDatabase(DataTable S2P5)
{
using (SqlConnection conn =New SqlConnection(@"Data Source=BL03\SQLEXPRESS; Initial Catalog=HDB; User Id=sa; Password=00"))
{
conn.Open();
foreach (DataRow importRow in S2P5.Rows)
{
SqlCommand cmd = new SqlCommand ("INSERT INTO S2P5 (DateTime, Miliseconds, MachineAutoStartStop, Pressure)" +
"VALUES (@DateTime, @Miliseconds, @MachineAutoStartStop, @Pressure)", conn);
cmd.Parameters.AddWithValue("@DateTime", (DateTime)importRow["DateTime"]); //error line
cmd.Parameters.AddWithValue("@Miliseconds", importRow["Miliseconds"]);
cmd.Parameters.AddWithValue("@MachineAutoStartStop", importRow["MachineAutoStartStop"]);
cmd.Parameters.AddWithValue("@Pressure", importRow["Pressure"]);
cmd.ExecuteNonQuery();
}
}
Jignesh KumarRank #91 · 22.9K reputationPosted Nov 29, 2022, 2:33 AM EST
Hello,
Please do this setting
Debug->Exceptions ... > Expand the MDA node and uncheck the box against contextswitchdeadlock .
refer this one,
https://social.msdn.microsoft.com/Forums/en-US/526c1640-95b4-490c-9dc1-36ee45048931/the-clr-has-been-unable-to-transition-from-com-context-0x1a1a90-to-com-context-0x1a1c00-for-60?forum=vblanguage
https://stackoverflow.com/questions/578357/visual-studio-contextswitchdeadlock
Jignesh KumarRank #91 · 22.9K reputationPosted Nov 28, 2022, 11:32 PM EST
Hello,
Please check by degugger, You are getting date value in that column or not. You have used DateTime as typecast so if you are getting null in that column then it will throw error, you need to check null before type cast it.
foreach (DataRow importRow in S2P5.Rows) { SqlCommand cmd = new SqlCommand ("INSERT INTO S2P5 (DateTime, Miliseconds, MachineAutoStartStop, Pressure)" + "VALUES (@DateTime, @Miliseconds, @MachineAutoStartStop, @Pressure)", conn); DateTime rowDate; if(DateTime.TryParse(importRow["DateTime"], out rowDate)) { cmd.Parameters.AddWithValue("@DateTime", rowDate); } else { cmd.Parameters.AddWithValue("@DateTime", DBNull.Value); } cmd.Parameters.AddWithValue("@Miliseconds", importRow["Miliseconds"]); cmd.Parameters.AddWithValue("@MachineAutoStartStop", importRow["MachineAutoStartStop"]); cmd.Parameters.AddWithValue("@Pressure", importRow["Pressure"]); cmd.ExecuteNonQuery(); }dhivyah jaiyasanger89 reputationPosted Nov 29, 2022, 2:20 AM EST
Problem Solve Ready.thank you sir.
but while i running the application i get this error;
Managed Debugging Assistant 'ContextSwitchDeadlock' : 'The CLR has been unable to transition from COM context 0x11a4278 to COM context 0x11a41c0 for 60 seconds. The thread that owns the destination context/apartment is most likely either doing a non pumping wait or processing a very long running operation without pumping Windows messages. This situation generally has a negative performance impact and may even lead to the application becoming non responsive or memory usage accumulating continually over time. To avoid this problem, all single threaded apartment (STA) threads should use pumping wait primitives (such as CoWaitForMultipleHandles) and routinely pump messages during long running operations.'