1

我正在尝试使我已经在表单视图的编辑页面中创建的下拉列表从先前从当前用户的 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 之外的其他东西吗)?谢谢!

4

2 回答 2

2

DropDownList尝试在 FormViewDataBound事件上实现选择项目的逻辑,该ModeChanging事件发生在模式实际更改之前。

于 2013-05-29T22:39:14.153 回答
0

您应该能够将 ddlSelect.SelectedValue 设置为您希望下拉菜单选择的值。

ddlSelect.SelectedValue = dt.Rows[0]["PN"].ToString();
于 2013-05-29T22:39:28.880 回答