如何在FormView编辑项模板中设置ASP.NET DropDownList.SelectedValue?

时间:2010-11-17 14:35:55

标签: c# asp.net formview

我正在尝试设置位于FormView的Edit模板内的DropDownList的选定值。每当我访问它时,我都会收到错误:

  

对象引用不存在

我正试图通过以下方式设置它:

DropDownList ddl = (DropDownList)FormView1.FindControl("ddlFrequency");
ddl.SelectedValue = "blah blah";

还喜欢:

((DropDownList)FormView1.FindControl("ddlFrequency")).SelectedValue = "blah blah";

如何设置此DropDownList.SelectedValue?

编辑:这是整个方法:

  protected void btnEdit_Click(object sender, EventArgs e)
{
    String frequency = ((Label)(FormView1.FindControl("lblFrequency"))).Text;

    FormView1.ChangeMode(FormViewMode.Edit);

    String selectedValue = "0";

    switch (frequency.ToLower())
    {
        case "none": selectedValue = "0"; break;
        case "daily": selectedValue = "1"; break;
        case "weekly": selectedValue = "7"; break;
        case "monthly": selectedValue = "28"; break;
        case "bi-monthly": selectedValue = "56"; break;
        case "quarterly": selectedValue = "84"; break;
        case "semi-annually": selectedValue = "168"; break;
        case "annually": selectedValue = "365"; break;
        default: break;
    }

    DropDownList ddl = (DropDownList)FormView1.FindControl("ddlFrequency");
    ddl.SelectedValue = selectedValue;
}

2 个答案:

答案 0 :(得分:1)

编辑模板必须可见才能使FindControl正常工作。您可能必须使用OnModeChanged事件来检查编辑模式,然后找到DropDownList。

答案 1 :(得分:1)