0

I wanted to insert data to microsoft access using c# and need to use class.

I've tried removing some textbox and look for some error and I feel that there might be some mistake in IF condition.

private void registerbutton_Click(object sender, EventArgs e)
{
    -- CLASS --
    RegStudent reg = new RegStudent();
    reg.stdfname = fnametextbox.Text;
    reg.stdlname = lnametextbox.Text;
    reg.username = usernametextbox.Text;
    reg.password = passwordtextbox.Text;
    reg.dob = dobtextbox.Text;
    reg.city = citytextbox.Text;
    reg.state = statetextbox.Text;
    reg.email = emailtextbox.Text;
    reg.phoneno = ctcnotextbox.Text;
    reg.phoneno2 = ctcnotextbox2.Text;
    reg.course = coursetextbox.Text;
    reg.emergencyname = emergencynametextbox.Text;
    reg.emergencyphoneno = emergencynumbertextbox.Text;
    reg.registerdate = registerdatetextbox.Text;
    if (tptextbox.Text != "" && fnametextbox.Text != "" && lnametextbox.Text != "" && dobtextbox.Text != "" && usernametextbox.Text != "" && passwordtextbox.Text != "" && citytextbox.Text != "" && statetextbox.Text != "" && registerdatetextbox.Text != "" && emailtextbox.Text != "" && ctcnotextbox.Text != "" && ctcnotextbox2.Text != "" && coursetextbox.Text != "" && emergencynametextbox.Text != "" && emergencynumbertextbox.Text != "")
    {
        registerconnection.Open();
        OleDbCommand insert = new OleDbCommand();
        insert.Connection = registerconnection;
        insert.CommandText = "Insert into StudentDatabase values (" + reg.stdfname + "','" + reg.stdlname + "','" + reg.username + "','" + reg.password + "','" + reg.dob + "','" + reg.city + "','" + reg.state + "','" + reg.email + "','" + reg.phoneno + "','" + reg.phoneno2 + "','" + reg.course + "','" + reg.emergencyname + "','" + reg.emergencyphoneno + ");";
        insert.CommandType = CommandType.Text;
        insert.Connection = registerconnection;
        insert.ExecuteNonQuery();
        MessageBox.Show("Data Have Been Registered.");
    }
    else
    {
        MessageBox.Show("error");
    }
}

I expected that the output will be that the data will be saved.

Jimi
  • 29,621
  • 8
  • 43
  • 61
  • 2
    Your `INSERT` command is missing the fields references. See the example in [OleDbDataAdapter.InsertCommand](https://learn.microsoft.com/en-us/dotnet/api/system.data.oledb.oledbdataadapter.insertcommand). You can of course use the `ExecuteNonQuery()` method, but focus on the command syntax and the use of Parameters. – Jimi Jun 05 '19 at 07:47
  • The answer [here](https://stackoverflow.com/questions/5893837/using-parameters-inserting-data-into-access-database) has a good example of inserting to an access database using parameters to avoid SQL injection. I realise this is probably an academic exercise, but you shouldn't store passwords in plain text either. – steve16351 Jun 05 '19 at 09:24
  • And date values should always be stored as _DateTime_. No exceptions. – Gustav Jun 05 '19 at 09:48

0 Answers0