user2939293
user2939293

Reputation: 813

How to store value from datepicker into string variable

I have a datepicker textbox. I want to store the date that is selected in the datepicker into a string variable, using c#. How will the code look like?

string date = datepicker.Text; //Does not work

I later in the code want to store the date into a database, like the following code:

string sql = "INSERT INTO tbl_mote (time, date, id) VALUES ('" + time + "','" + date + "','" + id + "')";
NpgsqlCommand command = new NpgsqlCommand(sql, conn);
int no = command.ExecuteNonQuery();

Datepicker:

<asp:TextBox ID="datepicker" runat="server"></asp:TextBox>

What happens is that todays date always saves into variable date and not the selected date.

Upvotes: 1

Views: 8662

Answers (3)

user2939293
user2939293

Reputation: 813

Ok, so here was the problem. I had included the code below in page load. Datepicker therefore always turned back to todays date, even if I changed it in the calender. After removing the line everything worked perfectly. Thanks all for your help!

datepicker.Text = DateTime.Now.ToShortDateString();

Upvotes: 0

George T
George T

Reputation: 708

1) Use datepicker.Value to get the selected date as a DateTime object. A DateTime object has several functions to produce a string for that date.

2) Do not, I repeat, do not concatenate strings for SQL parameters. Use parameters in the query (for SQL server they start with a @) and add values to the Command object later. I've not used an Npgsqlcommand but it must have a similar feature to SQL server SqlCommands.

3) You can use (1) to get a string value if you need it, but don't use it to insert into the database unless that specific database's objects don't understand DateTime objects. Use the DateTime object you got instead, as the value you add to the command object.

Upvotes: 2

Trajan
Trajan

Reputation: 339

The property you're looking for is SelectedDate:

string date = null;
if(datepicker.SelectedData.HasValue)
{
    date = datepicker.SelectedDate.Value.ToString("MM/dd/yyyy");
}
else
{
    // don't forget to define a default behavior. Your DB seems to choose today as a default date when the provided one doesn't fit. 
    // Even if that's ok for you, you should leave a comment to point it out to your colleagues/future self.
}

Besides, from a security point of view, you should consider using parameterized queries.

Upvotes: 0

Related Questions