DateTime型の値を挿入する方法[重複]

Nov 30 2020

私のテーブルには2つの列がStartedDateありEndDate、どちらもDateデータ型として定義されています。

以下に示すように、date型のテキストフィールドを介してこれら2つの列の値を挿入しようとしています。

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

これらのテキストボックスから値を取得して、データベースに挿入しようとしています。

これは挿入のための私のコードです:

// 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();

テキストボックスから取得した値をに変換する必要があるため、日付フィールドを除いて、挿入は問題なく機能しDateTimeます。

Convert.ToDateTimeDatetime.Parseメソッドを試しましたが、どちらの場合も次のエラーが発生します。

タイプ「System.DateTime」を「文字列」に暗黙的に変換することはできません

回答

Backs Nov 30 2020 at 11:00

DateTime.Parseメソッド:

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