Radek Tarant
Radek Tarant

Reputation: 227

How can I convert DateTimePicker to date for save to SQL Server?

Please, can you tell me how can I convert format DateTimePicker to date, because I can't save format DateTimePicker to database because the datatype in the database is only date.

Scripts:

public void addZam(SqlConnection sql, DateTimePicker denNastupu, DateTimePicker denUkonceni)

// Parameters
SqlParameter denNastupuParam = new SqlParameter("@denNastupu", SqlDbType.Date);
SqlParameter denUkonceniParam = new SqlParameter("@denUkonceni", SqlDbType.Date);

// Inicialization
denNastupuParam.Value = denNastupu;
denUkonceniParam.Value = denUkonceni;

// Add to parameters
addZam.Parameters.Add(denNastupuParam);
addZam.Parameters.Add(denUkonceniParam);

// Execute command
addZam.Prepare();
addZam.ExecuteNonQuery();

Format in DB:

datumNastupu date,
datumUkonceni date,

Error:

You can not convert parameter value from the DateTimePicker to DateTime

Can you offer me any opinion how can I fix it? Please.

Upvotes: 3

Views: 9444

Answers (1)

ken2k
ken2k

Reputation: 48985

Change your code to:

denNastupuParam.Value = denNastupu.Value;
denUkonceniParam.Value = denUkonceni.Value;

You want the value returned by your DateTimePicker control, not the control itself. If you're only interested in the Date part of the DateTime (not clear in the question), use denNastupu.Value.Date.

Upvotes: 3

Related Questions