SqlException: Conversion failed when converting date and/or time from character string

Last Reply 25 days ago By pandeyism

Posted 26 days ago

when i am inserting date into data base it giving error of 

Conversion failed when converting date and/or time from character string

my approach for inserting data into table from gridview

      protected void gvso_RowCommand(object sender, GridViewCommandEventArgs e)
      {          
          if (e.CommandName.Equals("Insert"))
          {
              TextBox txtaddorderref = (TextBox)gvso.FooterRow.FindControl("txtaddorderref");
              DropDownList ddlCusName = (DropDownList)gvso.FooterRow.FindControl("ddladdCustomerName");
              TextBox txtpirority = (TextBox)gvso.FooterRow.FindControl("txtaddSOpirority");
              TextBox ddlstatus = (TextBox)gvso.FooterRow.FindControl("txtstatusf");
              ddlstatus.Text = "Open";
              TextBox date = (TextBox)gvso.FooterRow.FindControl("txtaddOrder_date") ;
              // DateTime date1 = Convert.ToDateTime(date.Text);
 
              con = new SqlConnection("Data Source=ATLANTIC\\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=SilverProduction;MultipleActiveResultSets=True;");
 
              con.Open();
              SqlCommand ocmd = new SqlCommand();
              ocmd.CommandText = "INSERT INTO SalesOrder VALUES ('" + txtaddorderref.Text + "'," + ddlCusName.SelectedValue + ",'" + txtpirority.Text + "','" + ddlstatus.Text + "','" + date.Text + "','" + txtempid.Text + "')";
              
              ocmd.Connection = con;
              ocmd.ExecuteNonQuery();
              BindGrid(searchono.Text.Trim());
 
              con.Close();
          }
      }

 

Posted 25 days ago

Hi akhter,

Check below code it's working.

HTML

Date :
<asp:TextBox runat="server" ID="txtDate" />
<br />
<asp:Button Text="Insert" runat="server" OnClick="Save" />
<br />
<asp:GridView runat="server" ID="gvDates" runat="server" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="DateData" HeaderText="DateData" />
    </Columns>
</asp:GridView>

Namespaces

using System.Data.SqlClient;
using System.Data;
using System.Configuration;

Code

protected void Save(object sender, EventArgs e)
{
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    SqlConnection con = new SqlConnection(constr);
    SqlCommand cmd = new SqlCommand("INSERT INTO InsertDate VALUES(@Date)", con);
    cmd.Parameters.AddWithValue("@Date", txtDate.Text);
    con.Open();
    cmd.ExecuteNonQuery();
    con.Close();
    cmd = new SqlCommand("SELECT DateData FROM InsertDate", con);
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    DataTable dt = new DataTable();
    da.Fill(dt);
    gvDates.DataSource = dt;
    gvDates.DataBind();
}

Screenshot

Database