1

I'm trying to set the selected value of a DropDownList which sits inside the Edit template of a FormView. Whenever I access it, I get error:

Object reference doesn't exist

I'm trying to set it in the following ways:

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

And also like:

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

How can I set this DropDownList.SelectedValue?

EDIT: Here is the entire method:

  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;
}
MAW74656
  • 3,449
  • 21
  • 71
  • 118

2 Answers2

1

Well the edit template must be visible for FindControl to work. You will probably have to use the OnModeChanged event to check for the Edit mode and then find the DropDownList.

Matthew Jones
  • 25,644
  • 17
  • 102
  • 155
  • Did you solve this problem of yours? I am having the same problem not sure which way to go – Nita Dec 27 '13 at 16:51
1

Keep in mind FindControl() returns null on FormView until call DataBind() .

Community
  • 1
  • 1
abatishchev
  • 98,240
  • 88
  • 296
  • 433