我需要使用小时和分钟填充2下拉列表。我目前填充下拉列表的方法并没有正确格式化数字,因为我要求前9个数字的前导0,即01,02,03,而不是当前正在发生的1,2,3。
C#
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
if (!IsPostBack)
{
// Populate and Bind Time drop downs
ddlOh1OpenHours.DataSource = Enumerable.Range(00, 24);
ddlOh1OpenHours.DataBind();
ddlOh1OpenMinutes.DataSource = Enumerable.Range(00, 60);
ddlOh1OpenMinutes.DataBind();
}
}
ASPX
<asp:DropDownList ID="ddlOh1OpenHours" runat="server" />
<span>:</span>
<asp:DropDownList ID="ddlOh1OpenMinutes" runat="server" />
结果:
<select name="ctl00$MainContent$ddlOh1OpenHours" id="ctl00_MainContent_ddlOh1OpenHours">
<option selected="selected" value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
<option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
<option value="21">21</option>
<option value="22">22</option>
<option value="23">23</option>
</select>
答案 0 :(得分:10)
只需使用正确格式的ToString
:
var hours = Enumerable.Range(00, 24).Select(i => i.ToString("D2"));
var minutes = Enumerable.Range(00, 60).Select(i => i.ToString("D2"));
dlOh1OpenHours.DataSource = hours;
ddlOh1OpenHours.DataBind();
ddlOh1OpenMinutes.DataSource = minutes;
ddlOh1OpenMinutes.DataBind();