Ibrahim Shaikh Ibrahim Shaikh - 9 months ago 64
C# Question

Convert Date type C#

I am Creating A Web app I am using a textbox and textbox calender extender to get the date enter by the user, I want Date in this


but I am getting error

(Arithmetic overflow error converting expression to data type

By Default the format of the date is

protected void txttodate_TextChanged(object sender, EventArgs e)
string com = Convert.ToString(Session["radio"]);
string com1 = Convert.ToString(Session["mysession"]);
Session["drd3"] = com.ToString();
Session["lblname"] = com1.ToString();

SqlCommand cmdtr = new SqlCommand("select empname from trainerdetails where trid='"+com1.ToString()+"'",con);
SqlDataReader dr = cmdtr.ExecuteReader();
while (dr.Read())
lblempname.Text = dr["empname"].ToString();
GridView1.Visible = true;
connectionstr = WebConfigurationManager.ConnectionStrings["Constr"].ConnectionString;
con = new SqlConnection(connectionstr);
SqlCommand cmd = new SqlCommand("csuvdaterange");
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
SqlParameter[] param =
new SqlParameter("@logintype",com.ToString()),
new SqlParameter("@name",lblempname.Text),
new SqlParameter("@datefrm",txtfrmdate.Text),
new SqlParameter("@dateto",txttodate.Text)
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
GridView1.DataSource = ds;

This Is How My Backend Code looks

<asp:TextBox ID="txtfrmdate" Visible="false" runat="server" placeholder="From" style="margin-left:10px; margin-top:8px;" Height="30px" Width="200px"></asp:TextBox>
<asp:CalendarExtender ID="calenderfromextend" TargetControlID="txtfrmdate" runat="server" Format="dd-MM-yyyy"></asp:CalendarExtender>
<asp:TextBox ID="txttodate" placeholder="To" Visible="false" runat="server" style="margin-left:10px; margin-top:8px;" AutoPostBack="true" OnTextChanged="txttodate_TextChanged" Height="30px" Width="200px"></asp:TextBox>
<asp:CalendarExtender ID="calendertoextend" TargetControlID="txttodate" runat="server" Format="dd-MM-yyyy"></asp:CalendarExtender>

My Textboxes and calender extender


After Implementing Jon's suggestions on using Parameterised SQL, using using statements and if you are sure that the dates entered in TextBox are in format "yyyy-MM-dd", you may use this code to change the format string:

SqlParameter[] param =
    new SqlParameter("@logintype",com.ToString()),
    new SqlParameter("@name",lblempname.Text),
    new SqlParameter("@datefrm",DateTime.ParseExact(txtfrmdate.Text, "dd-MM-yyyy", CultureInfo.InvariantCulture).ToString("yyyy-MM-dd")),
    new SqlParameter("@dateto",DateTime.ParseExact(txttodate.Text, "dd-MM-yyyy", CultureInfo.InvariantCulture).ToString("yyyy-MM-dd"))