0

I have a DateTimePicker(dtp) and an Add Button.

I saved 'birthday' as 'date' in my database.

Now I dont know how to save the data from dtp into database after click Add button.

Please help. Thank you. Here is my wrong code with error:

conversion failed when converting date and/or time from character string

private void btnAdd_Click(object sender, EventArgs e)
        {
                cnn.Open();
                DateTime dtp_text = Convert.ToDateTime(dtp.Text);

                int gt = 0;
                if (rdoMale.Checked == true)
                    gt = 1;
                else if (rdoFemale.Checked == true)
                    gt = 0;
                string sql = "insert into NV values ('" + txtId.Text + "', N'" + txtName.Text + "',N'" + dtp_text + "')";
                SqlCommand ins = new SqlCommand(sql, cnn);
                ins.CommandType = CommandType.Text;
                ins.ExecuteNonQuery();
                Load();
                cnn.Close();
        }
Ben
  • 135
  • 1
  • 2
  • 8
  • 1
    Use a parameterized query with a `SqlDbType.DateTime` parameter and use `dtp.Value` as the parameter value. You should change the entire query to use parameters too. – Dan Guzman Apr 19 '19 at 15:40
  • Before you write another line of code you need to read about, understand and start using parameterized queries. Your code is wide open to sql injection. Fix this before my firend [bobby tables](http://bobby-tables.com/) comes to visit. – Sean Lange Apr 19 '19 at 15:40
  • Use a parameter : https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlcommand.parameters?view=netframework-4.8 – jdweng Apr 19 '19 at 15:42
  • 1
    `dtp.Value` is already a `DateTime`. You don't need to convert the `Text`. – Rufus L Apr 19 '19 at 15:47
  • Also you don't need `else if`, this is good enough: `int gt = 0; if (rdoMale.Checked == true) { gt = 1; }` – CodingYoshi Apr 19 '19 at 15:52

0 Answers0