Search code examples
c#ms-accessvisual-studio-2013windowsformsintegration

C# Error - Argument Exception was Unhandled


I am writing a patient booking application, and when I click my button, it's supposed to add 365 days (from today) to my Access file under the column Day1.

Now, it was working before, but now it is giving me an error.

An unhandled exception of type 'System.ArgumentException' occurred in System.Data.dll

Additional information: Format of the initialization string does not conform to specification starting at index 34.

Code:

private void button3_Click(object sender, EventArgs e)
{
        DateTime a = dateTimePicker1.Value.Date;
  HERE-> System.Data.OleDb.OleDbConnection conn = new
System.Data.OleDb.OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data
SourceC:\Users\Kolton\Desktop\Doctor App\Database1.accdb"); <- TO HERE

        conn.Open();

        for (int i = 0; i < 366; i++)
        {
            DateTime b = a.AddDays(i);
            string c = b.ToShortDateString();

            using (System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand())
            {
                cmd.Connection = conn;
                cmd.CommandText = "Insert Into Times (Date1) values ('" + c + "')";

                cmd.ExecuteNonQuery();
            }
        }
    }

Any help is appreciated.

Also, trying to kill two birds with one stone here. As a bonus question, is it possible to make this button delete all the rows under the column (Date1) and then make it add the 365 days to it?

Thanks.


Solution

  • import this at top

    System.Data.OleDb;

    private void button3_Click(object sender, EventArgs e)
    {
     DateTime a = dateTimePicker1.Value.Date;
    
     using(OleDbConnection conn = new
     OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data
     Source=C:\Users\Kolton\Desktop\Doctor App\Database1.accdb")) 
     {
            for (int i = 0; i < 366; i++)
            {
                DateTime b = a.AddDays(i);
                string c = b.ToShortDateString();
    
                using (System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand())
                {
                    cmd.Connection = conn;
                    cmd.CommandText = "Insert Into Times (Date1) values ('" + c + "')";
                    conn.Open();
                    cmd.ExecuteNonQuery();
                }
    
            }
        }
      }
    
    1. Set your connection string
    2. Import System.Data.OledDB
    3. Use Using for connection as well
    4. It Would be better if you use parameterize query