Click here to Skip to main content
15,883,705 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
error:System.InvalidCastException: 'Specified cast is not valid.'

csv data:
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.382796

error line: cmd.Parameters.AddWithValue("@DateTime", (DateTime)importRow["DateTime"]);

What I have tried:

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"]);
        cmd.Parameters.AddWithValue("@Miliseconds", importRow["Miliseconds"]);
        cmd.Parameters.AddWithValue("@MachineAutoStartStop", importRow["MachineAutoStartStop"]);
        cmd.Parameters.AddWithValue("@Pressure", importRow["Pressure"]);

        cmd.ExecuteNonQuery();
    }
}
Posted
Updated 25-Nov-22 3:45am
v2

YOu can;t cast a random - or more likely string - value to a DateTime, you need to parse it instead.
I'd use DateTime.TryParse[^] or DateTime.TryParseExact[^] to convert the CSV based value, and it is succeeds, pass the resulting DateTime value to SQL.
 
Share this answer
 
Comments
dhivyah jaiya 29-Nov-22 2:26am    
problem solved.Thank you for your solution.
OriginalGriff 29-Nov-22 2:31am    
You're welcome!

You have to format the date string so that it can be converted into a DateTime instance. You need to be careful that the milliseconds do not get truncated during the conversion.Something along these lines should do the trick.

C#
string myDateAsString = "25/10/2022 10:31 787";
DateTime myDateAsDateTime = DateTime.ParseExact(myDateAsString, "dd/MM/yyyy HH:mm fff",
                                                           CultureInfo.InvariantCulture);

 
Share this answer
 
Comments
dhivyah jaiya 29-Nov-22 2:25am    
thank your for the solution.the problem solved ready.

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