我有一个<asp:TextBox>
,我用SQL表中的日期值隐藏了它。
预计:2017年5月23日
结果:05/23/2017 12:00:00 AM
以下是TextBox
和绑定的代码:
<asp:TextBox ID="txtDateOrdered" runat="server" class="form-control" ReadOnly="true" />
void GetOrderHead(int ID)
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT * FROM Orders WHERE OrderNo=@OrderNo";
cmd.Parameters.AddWithValue("@OrderNo", ID);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
ltID.Text = dr["OrderNo"].ToString();
txtOrderNo.Text = dr["OrderNo"].ToString();
txtDateOrdered.Text = dr["DateOrdered"].ToString();
txtPreparedBy.Text = dr["PreparedBy"].ToString();
txtStatus.Text = dr["Status"].ToString();
txtBalance.Text = dr["Balance"].ToString();
txtTotal.Text = dr["TotalAmount"].ToString();
}
con.Close();
}
else
{
con.Close();
Response.Redirect("Default.aspx");
}
}
注意:我使用.ToString("MM/dd/yyyy");
&amp;找到了答案。 .ToShortDateString();
并且两者都无效。
答案 0 :(得分:0)
尝试以下代码:
void GetOrderHead(int ID)
{
string[] formats= { "MM/dd/yyyy" }
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT * FROM Orders WHERE OrderNo=@OrderNo";
cmd.Parameters.AddWithValue("@OrderNo", ID);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
ltID.Text = dr["OrderNo"].ToString();
txtOrderNo.Text = dr["OrderNo"].ToString();
txtDateOrdered.Text = DateTime.ParseExact(dr["DateOrdered"].ToString(), formats, new CultureInfo("en-US"), DateTimeStyles.None); //changing format.
txtPreparedBy.Text = dr["PreparedBy"].ToString();
txtStatus.Text = dr["Status"].ToString();
txtBalance.Text = dr["Balance"].ToString();
txtTotal.Text = dr["TotalAmount"].ToString();
}
con.Close();
}
else
{
con.Close();
Response.Redirect("Default.aspx");
}
}
答案 1 :(得分:0)
您还可以在Sql Query中更改日期格式。
SELECT OrderNo, CONVERT(VARCHAR(101), DateOrdered) as DateOrdered, PreparedBy, Status, Balance, TotalAmount FROM Orders WHERE OrderNo = @OrderNo
使用DateTime.ParseExact
或解析日期时间
DateTime.ParseExact(dr["DateOrdered"].ToString(), "MM/dd/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None);