[英]How to Use DateTime Web Form Field to Pass DateTime Parameter into Database using Stored Procedure?
我正在嘗試在網絡表單中使用datetime字段將datetime參數傳遞到數據庫中。
數據庫中的日期時間格式為:
2015-05-18 00:00:00.000
Webform輸入字段為:
<asp:TextBox ClientIDMode="Static" ID="txtEffDate" runat="server" CssClass="calendarImg" Width="100px"></asp:TextBox>
<asp:ImageButton runat="Server" ID="ImageButton1" ImageUrl="~/images/cal.gif" BorderStyle="None"
AlternateText="Click to show calendar" TabIndex="300" Style="cursor: pointer;" Width="16px" />
<asp:CalendarExtender ID="CalendarExtender1" runat="server" TargetControlID="txtEffDate" PopupButtonID="ImageButton1" />
后面的特定參數代碼為:
cmd.Parameters.Add("@desiredEffDate", SqlDbType.DateTime).Value = txtEffDate;
存儲過程中的特定參數為:
@desiredEffDate datetime,
如何正確定義日期時間或在后面的代碼中將其轉換為正確的格式?
謝謝你的幫助!
首先,我建議使用更好的控件,或者在文本框控件中設置HTML5屬性類型:
<asp:TextBox ClientIDMode="Static" ID="txtEffDate" runat="server" CssClass="calendarImg" Width="100px" type="date"></asp:TextBox>
您可以嘗試像這樣轉換日期:
DateTime effDate;
Try {
effDate = DateTime.Parse(txtEffDate);
} Catch (FormatException ex) {
// invalid date string
}
除非您有錯字,否則您將試圖將sql參數值設置為文本框對象,而不是文本框的值。 您應該使用txtEffDate.Text
獲得它的值。 假設您的文本框值只能設置為日期時間格式(通過日期時間選擇器或設置type屬性,但此時后者與前者的瀏覽器兼容性不同),則應將其轉換為在SQL中正確設置為日期時間。 也可以使用以前發布的答案提供的功能將其轉換為.NET日期時間。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.