ASP.NET中如何将数据库值设置到type=Date的文本框?
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:
Don't directly assign to
Attributes
Your linetxtDOB.Attributes = tempRow["DOB"].ToString();is incorrect. TheAttributesproperty 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 theTextproperty is the right way to go.Format the date correctly
You need to convert the value from your database into the requiredyyyy-MM-ddformat. 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

