Formatting data using the DataFormatString property in C# data binding.
In C#, you can specify the format of data binding using the DataFormatString property. This property, which is a string, can include placeholders and formatting strings. Here are some common formatting strings:
- {0}: represents the bound value.
- {0:n}: Represents numbers, separates thousands with commas, and keeps two decimal places.
- {0:c}: Represents currency, using currency symbol and comma to separate thousands, with two decimal places.
- {0:d} represents the date in a short date format.
- {0:D} : represents the date in the long date format.
- {0:t}: Represents time, in short time format.
- {T}: indicates time, using the long time format.
Here are some examples:
// 数字格式化为货币
Label1.Text = String.Format("{0:c}", 123456.789); // 输出:¥123,456.79
// 数字格式化为百分比
Label2.Text = String.Format("{0:p}", 0.123); // 输出:12.30%
// 日期格式化为短日期
Label3.Text = String.Format("{0:d}", DateTime.Now); // 输出:2022/1/1
// 日期格式化为长日期
Label4.Text = String.Format("{0:D}", DateTime.Now); // 输出:2022年1月1日
// 时间格式化为短时间
Label5.Text = String.Format("{0:t}", DateTime.Now); // 输出:上午12:00
// 时间格式化为长时间
Label6.Text = String.Format("{0:T}", DateTime.Now); // 输出:上午12:00:00
These formatting strings can be used in the DataFormatString property of data-bound controls to format the bound data. For example:
<asp:Label ID="Label7" runat="server" Text='<%# Bind("Price", "{0:c}") %>'></asp:Label>
The above code formats the bound data into currency form.