【问题标题】:How do you populate dynamic dropdowns based on a number field in database?如何根据数据库中的数字字段填充动态下拉列表?
【发布时间】:2018-05-13 06:04:51
【问题描述】:

我正在尝试实现一个下拉菜单,其中包含数字 1 - 数据库中的值

我可以在下拉列表中显示数据库中的值,但无法获取从 1 开始的数字以作为下拉列表中的选项创建。

下面是我的asp代码:

    <asp:SqlDataSource
    ID="selectSprintLength"
    runat="server"
    ConnectionString="<%$ ConnectionStrings:scConnection %>"
    SelectCommand="SELECT * FROM sc_sprints WHERE scSprintID = @sprint">
    <SelectParameters>
        <asp:QueryStringParameter QueryStringField="sprint" Name="sprint" Type="String" />
    </SelectParameters>
</asp:SqlDataSource>

<asp:DropDownList ID="sprintLengthDropDown"
    runat="server"
    OnSelectedIndexChanged="sprintDropDown_SelectedIndexChanged"
    DataSourceID="selectSprintLength"
    DataTextField="scSprintTotal"
    DataValueField="scSprintTotal"
    AutoPostBack="true"
    EnableViewState="true" />

这是我的 C# 代码:

protected void sprintDropDown_SelectedIndexChanged(object sender, EventArgs e)
{
    int counter = 0;
    int x = Int32.Parse(sprintLengthDropDown.SelectedValue);
    do
    {
         counter++;
    }
    while (counter < x);
}

任何人都可以帮忙,以便值 1 - scSprintTotal 是下拉列表中的所有选项。例如 scSprintTotal 为 7,下拉值将为 1、2、3、4、5、6、7。

提前致谢!

【问题讨论】:

    标签: c# mysql sql asp.net


    【解决方案1】:
     int items;
        protected void Page_Load(object sender, EventArgs e)
        {
            SqlCommand cmd = new SqlCommand("SELECT * from scSprint",con);
            con.Open();
            SqlDataReader dr = cmd.ExecuteReader();
            if (dr.Read())
            {
                Label1.Text = "The total is " + dr["scsprinttotal"].ToString(); 
                items = Convert.ToInt32(dr["scsprinttotal"].ToString());
            }
            con.Close();
            for (int i = 1; i <= items;i++ )
            {
                DropDownList1.Items.Add(i.ToString());
            }
    
        }
    

    【讨论】:

      【解决方案2】:

      要使用系列值填充下拉列表,我们可以使用 Enumerable.Range(starting_number, range);请看教程https://www.dotnetperls.com/enumerable-range

      sprintLengthDropDown.DataSource = Enumerable.Range(1, 7);
      sprintLengthDropDown.DataBind();
      

      您可以将范围动态设置为数据库中的值。

      【讨论】:

      • 请将答案标记为正确答案以及有用的答案。谢谢!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-09
      • 2013-06-20
      • 2019-06-24
      • 2015-03-21
      • 2021-05-19
      • 2017-08-03
      • 1970-01-01
      相关资源
      最近更新 更多