我有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();
}
}
答案 0 :(得分:0)
我疯狂的猜测是,读者是基于流的,只有转发,第一个绑定成功迭代数据,而后续绑定发现数据流结束。
我会尝试将数据复制到数组中并尝试绑定到数组。这是一个可能有用的问题。