我正在创建一个Web应用程序我正在使用文本框和文本框日历扩展程序来获取用户输入的日期,我想要这个("dd-MM-yyyy")
格式的日期,
但我收到错误
(将表达式转换为数据类型的算术溢出错误 日期时间。)
默认情况下,日期格式为("yyyy-MM-dd")
此
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);
con.Open();
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)
};
cmd.Parameters.AddRange(param);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
这是我的后端代码的外观
<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和calender extender
答案 0 :(得分:2)
在实施Jon关于使用参数化SQL 的建议后,使用using
语句并确定TextBox
中输入的日期格式为&# 34; yyyy-MM-dd
&#34;,您可以使用此代码更改格式字符串:
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"))
};
答案 1 :(得分:0)
首先通过DateTime.ParseExact
var dateFrom = DateTime.ParseExact(txtfrmdate.Text, "dd-MM-yyyy", null);
var dateTo = DateTime.ParseExact(txttodate.Text, "dd-MM-yyyy", null);
之后,请替换为SqlParameter
:
SqlParameter[] param =
{
new SqlParameter("@logintype",com.ToString()),
new SqlParameter("@name",lblempname.Text),
new SqlParameter("@datefrm",SqlDbType.DateTime) { Value = dateFrom },
new SqlParameter("@dateto", SqlDbType.DateTime) { Value = dateTo }
};
答案 2 :(得分:-1)
String.Format("{0:MM/dd/yyyy}", dt);