Cách chèn giá trị kiểu DateTime [trùng lặp]

Nov 30 2020

Trong bảng của tôi, tôi có hai cột StartedDateEndDatecả hai cột đều được định nghĩa là Datekiểu dữ liệu.

Tôi đang cố gắng chèn các giá trị cho hai cột này thông qua trường văn bản của loại ngày như được hiển thị bên dưới:

<asp:Textbox type="date" ID="startDate" runat="server"></asp:Textbox>
<asp:Textbox type="date" ID="endDate"  runat="server"></asp:Textbox>

Tôi đang cố gắng lấy giá trị từ các hộp văn bản này và chèn chúng vào cơ sở dữ liệu của mình.

Đây là mã của tôi cho phần chèn:

// Insert a new row in the Task table
SqlDataSource1.InsertParameters["Task"].DefaultValue = ((TextBox)GridView1.FooterRow.FindControl("txtTask")).Text;
SqlDataSource1.InsertParameters["StartedDate"].DefaultValue = ((TextBox)GridView1.FooterRow.FindControl("startDate")).Text;
SqlDataSource1.InsertParameters["EndDate"].DefaultValue = ((TextBox)GridView1.FooterRow.FindControl("endDate")).Text;
SqlDataSource1.InsertParameters["Done"].DefaultValue = ((CheckBox)GridView1.FooterRow.FindControl("DoneCbx")).Checked == true ? "true" : "false";
SqlDataSource1.InsertParameters["Priority"].DefaultValue = ((TextBox)GridView1.FooterRow.FindControl("PriorityTxt")).Text;

// Method to execute the insert 
SqlDataSource1.Insert();

Chèn hoạt động tốt, ngoại trừ các trường ngày tháng vì giá trị được truy xuất từ ​​hộp văn bản cần được chuyển đổi thành DateTime.

Tôi đã thử Convert.ToDateTimeDatetime.Parsecác phương pháp, nhưng cả hai lần tôi đều gặp lỗi sau:

Không thể chuyển đổi hoàn toàn kiểu 'System.DateTime' thành 'string'

Trả lời

Backs Nov 30 2020 at 11:00

Phương thức DateTime.Parse :

SqlDataSource1.InsertParameters["StartedDate"].DefaultValue = DateTime.Parse(((TextBox)GridView1.FooterRow.FindControl("startDate")).Text);