如何将datepicker中的值存储到字符串变量中

时间:2014-04-22 07:41:59

标签: c# asp.net

我有一个datepicker文本框。我想使用c#将datepicker中选择的日期存储到字符串变量中。 代码将如何?

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

我稍后在代码中想要将日期存储到数据库中,如下面的代码:

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

日期选择器:

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

今天的日期总是保存到变量日期而不是选定的日期。

3 个答案:

答案 0 :(得分:2)

1)使用datepicker.Value将所选日期作为DateTime对象。 DateTime对象有几个函数可以为该日期生成字符串。

2)不要重复,不要为SQL参数连接字符串。在查询中使用参数(对于以@开头的SQL服务器),稍后将值添加到Command对象。我没有使用过Npgsqlcommand,但它必须具有与SQL server SqlCommand类似的功能。

3)如果需要,可以使用(1)获取字符串值,但不要使用它来插入数据库,除非特定数据库的对象不理解DateTime对象。使用您获得的DateTime对象作为您添加到命令对象的值。

答案 1 :(得分:0)

您正在寻找的属性是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.
}

此外,从安全角度来看,您应该考虑使用parameterized queries

答案 2 :(得分:0)

好的,这就是问题所在。我在页面加载中包含了以下代码。因此,Datepicker总是回到今天的日期,即使我在日历中更改了它。删除线后一切都很完美。 谢谢大家的帮助!

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