You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET中如何将数据库值设置到type=Date的文本框?

Fixing Date Input for type="Date" TextBox

Hey there! Let's get that date showing up in your type="Date" textbox properly. The main issue here is how HTML5 date inputs handle date values, plus a couple of small code mistakes. Here's what you need to know:

Key Background: HTML5 Date Input Format

HTML5's type="date" input only accepts dates in the ISO 8601 standard format: yyyy-MM-dd (e.g., 2024-05-20). It doesn't matter what your local date format is—browsers will ignore any other format, which is probably why your current code isn't working.

Fixing Your Code

Let's break down the problems in your current approach and fix them:

  1. Don't directly assign to Attributes
    Your line txtDOB.Attributes = tempRow["DOB"].ToString(); is incorrect. The Attributes property is a collection of key-value pairs, not a single string. You don't need to mess with this for a standard ASP.NET TextBox—setting the Text property is the right way to go.

  2. Format the date correctly
    You need to convert the value from your database into the required yyyy-MM-dd format. Here's how to do it properly:

If your database stores DOB as a DateTime type:

// Convert the database value to a DateTime first
DateTime dob = Convert.ToDateTime(tempRow["DOB"]);
// Format it to ISO 8601 and assign to the Text property
txtDOB.Text = dob.ToString("yyyy-MM-dd");

If your database stores DOB as a string:

First validate and parse the string to avoid errors, then format it:

string dobString = tempRow["DOB"].ToString();
if (DateTime.TryParse(dobString, out DateTime dob))
{
    txtDOB.Text = dob.ToString("yyyy-MM-dd");
}
else
{
    // Handle invalid date cases (e.g., set empty or show error)
    txtDOB.Text = string.Empty;
}

Double-Check Your ASPX Markup

Make sure your TextBox is explicitly set to type="date" in your ASPX file:

<asp:TextBox ID="txtDOB" runat="server" type="date"></asp:TextBox>

That should do it! Once you format the date correctly and use the Text property properly, the date should show up in the textbox as expected.

内容的提问来源于stack exchange,提问作者user3524014

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:37:44