选择下拉列表的初始值
本文关键字:下拉列表 选择 | 更新日期: 2023-09-27 18:16:03
我正试图使下拉列表我已经创建了一个formview的编辑页面内开始的值以前从sql数据库为当前用户选择。
到目前为止,我已经有了正确填充下拉列表的代码:protected void ddlSelect_Init(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ReinstatementCS"].ConnectionString);
SqlCommand myCommand = new SqlCommand("SELECT Prefix, Number, ClassSection, Location, StartTime, EndTime, ClassDay, Prefix + Number + ', Section: ' + CAST(ClassSection AS VarChar) + ', Location: ' + Location + ', Start Time: ' + StartTime + ', End Time: ' + EndTime + ', Days: ' + ClassDay + ', Credits: ' + CAST(ClassCredit AS VarChar) AS PN, Capacity, GPAReqAbove1, GPAReqBelow1, CreditReqAbove30, CreditReqBelow30, ClassCredit, IsTransfer, SLN FROM Classes");
myCommand.Connection = con;
SqlDataAdapter da = new SqlDataAdapter(myCommand);
DataTable dt = new DataTable();
da.Fill(dt);
DropDownList ddlSelect = FVStudentClass.FindControl("ddlSelect") as DropDownList;
ddlSelect.DataSource = dt;
ddlSelect.DataTextField = "PN";
ddlSelect.DataValueField = "SLN";
ddlSelect.DataBind();
con.Close();
}
其中SLN为下拉列表中每一项的唯一值,PN为下拉列表中每一项的背景信息。我希望突出显示的项目是对应于特定用户已经存储在数据库中的PN。问题是,当我尝试选择该值时,我使用:
protected void FVStudentClass_ModeChanging(object sender, FormViewCommandEventArgs e)
{
if (FVStudentClass.CurrentMode != FormViewMode.Edit)
return;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ReinstatementCS"].ConnectionString);
SqlCommand myCommand = new SqlCommand("SELECT Prefix + Number + ', Section: ' + CAST(ClassSection AS VarChar) + ', Location: ' + Location + ', Start Time: ' + StartTime + ', End Time: ' + EndTime + ', Days: ' + ClassDay + ', Credits: ' + CAST(ClassCredit AS VarChar) AS PN, SLN FROM Classes JOIN StudentClass on SLN = SCClass WHERE SCWSUID = " + Request.QueryString["ALWSUID"]);
myCommand.Connection = con;
SqlDataAdapter da = new SqlDataAdapter(myCommand);
DataTable dt = new DataTable();
da.Fill(dt);
DropDownList ddlSelect = new DropDownList();
ddlSelect = FVStudentClass.FindControl("ddlSelect") as DropDownList;
if (ddlSelect != null)
{
ddlSelect.DataSource = dt;
ddlSelect.Items.FindByText(dt.Rows[0]["PN"].ToString()).Selected = true;
}
con.Close();
}
,但我仍然卡住了,因为下拉列表不开始与保存的值被选中。你知道怎么解决吗?我是否使用了错误的命令(我应该使用除了ModeChanging之外的东西吗)?谢谢!
尝试实现在FormView DataBound
事件上选择DropDownList
项的逻辑,ModeChanging
事件发生在模式实际改变之前
您应该能够直接设置ddlSelect。SelectedValue为您希望下拉菜单选择的值。
ddlSelect.SelectedValue = dt.Rows[0]["PN"].ToString();