I figured out I'm not parsing Date value as I should. But I'm unsure on how to do it.
I know I should manually parse date value, but to be honest I don't know how to do it.
private void BtnDodajDavaoca_Click(object sender, EventArgs e)
{
String query = "INSERT INTO Davaoci (Ime,Prezime,Pol,DatumRodjenja,KrvnaGrupa,Tezina,Adresa,BrojTel,BrojLK) VALUES (@Ime, @Prezime, @Pol, @DatumRodjenja, @KrvnaGrupa, @Tezina, @Adresa, @BrojTel, @BrojLK)";
using (SqlConnection cs = new SqlConnection(@"Data Source=DESKTOP-112OILD\SQLEXPRESS;Initial Catalog=DDK;Integrated Security=True"))
using (SqlCommand InsertDavaoc = new SqlCommand(query, cs))
{
InsertDavaoc.Parameters.Add("@Ime", SqlDbType.NVarChar).Value = TxtIme.Text;
InsertDavaoc.Parameters.Add("@Prezime", SqlDbType.NVarChar).Value = TxtPrezime.Text;
InsertDavaoc.Parameters.Add("@Pol", SqlDbType.NChar).Value = TxtPol.Text;
//IT'S THIS LINE InsertDavaoc.Parameters.Add("@DatumRodjenja", SqlDbType.Date).Value = DtpDatumRodjenja.Text;
InsertDavaoc.Parameters.Add("@KrvnaGrupa", SqlDbType.VarChar).Value = TxtKrvnaGrupa.Text;
InsertDavaoc.Parameters.Add("@Tezina", SqlDbType.Float).Value = TxtTezina.Text;
InsertDavaoc.Parameters.Add("@Adresa", SqlDbType.NVarChar).Value = TxtAdresa.Text;
InsertDavaoc.Parameters.Add("@BrojTel", SqlDbType.NVarChar).Value = TxtBrojTel.Text;
InsertDavaoc.Parameters.Add("@BrojLK", SqlDbType.NVarChar).Value = TxtBrojLK.Text;
cs.Open();
InsertDavaoc.ExecuteNonQuery();
cs.Close();
OsvjeziDgDavaoci();
ClearTxtBx();
}
}
The safe way in converting a string to a date is to use the ParseExact
method, that allow you to specify the format in a deterministic way:
// Use custom formats with M and MM.
var dateString = "5/01/2009 09:00";
try {
dateValue = DateTime.ParseExact(dateString, "M/dd/yyyy hh:mm", enUS, DateTimeStyles.None);
Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue,
dateValue.Kind);
}
catch (FormatException) {
Console.WriteLine("'{0}' is not in an acceptable format.", dateString);
}
因此,必须使用DatePicker而不是TextBox,但是可以使用Parse Method将字符串解析为DateTime:
DateTime.Parse(TxtDatumRodjenja.Text);
您还可以使用以下代码将字符串日期转换为与点网兼容的日期对象,例如
InsertDavaoc.Parameters.Add("@DatumRodjenja", SqlDbType.Date).Value = Convert.ToDateTime(DtpDatumRodjenja.Text);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.