【问题标题】:Populate a number of DropDownLists with MySQL reader使用 MySQL 阅读器填充多个 DropDownLists
【发布时间】:2014-09-13 04:03:34
【问题描述】:

我有 10 个 DropDownLists(ddlQuestion1IDs、ddlQuestion2IDs、ddlQuestion3IDs...),我想用数据库中的数据填充它们。但是,以下代码仅填充 ddlQuestion1ID。为什么会这样?用相同数据填充所有 10 个数据的最有效方法是什么?

protected void getQuestionIDs()
{
    string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
    MySqlConnection conn = new MySqlConnection(connStr);
    MySqlDataReader reader;

    string cmdText = "SELECT * FROM questions WHERE module_id=@ModuleID";
    MySqlCommand cmd = new MySqlCommand(cmdText, conn);
    cmd.Parameters.Add("@ModuleID", MySqlDbType.Int32);
    cmd.Parameters["@ModuleID"].Value = ddlModules.SelectedValue;

    try
    {
        conn.Open();
        reader = cmd.ExecuteReader();
        for (int i = 1; i <= 10; i++)
        {
            var ddlQuestion = (DropDownList)FindControl("ddlQuestion" + i.ToString() + "IDs");
            ddlQuestion.DataSource = reader;
            ddlQuestion.DataValueField = "question_id";
            ddlQuestion.DataTextField = "question_id";
            ddlQuestion.DataBind();
            ddlQuestion.Items.Insert(0, new ListItem(string.Empty, "blank"));
        }
        reader.Close();
    }
    catch
    {
        lblError.Text = "Database connection error - failed to get question IDs.";
    }
    finally
    {
        conn.Close();
    }
}

【问题讨论】:

  • 为什么不使用单个变量而不是始终搜索同一个控件?这会更有效,而且——更重要的是——更具可读性。 var ddlQuestion = (DropDownList)FindControl("ddlQuestion" + i.ToString() + "IDs"); // set all properties...
  • @TimSchmelter 已修改。谢谢,尽管当我真正想要填充所有十个时,仍然只有第一个 DropDownList 被填充。
  • 我会使用MySqlDataAdapter 来填充DataTable 并将其用作DataSource

标签: c# mysql asp.net loops drop-down-menu


【解决方案1】:

我的疯狂猜测是阅读器是基于流的,仅向前的,第一个绑定成功地迭代数据,而后续绑定发现数据流位于末尾。

我会尝试将数据复制到数组中并尝试绑定到数组。这是一个可能有帮助的问题。

Can I reset and loop again through MySqlDataReader?

【讨论】:

    猜你喜欢
    • 2018-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多