当 ASP.NET DropDownList.SelectedValue 位于 FormView 编辑项模板内时,如何设置它?
我正在尝试设置位于 FormView 的编辑模板内的 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;
}
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
请记住 FindControl() 在 FormView 上返回 null,直到调用 DataBind() 。
Keep in mind FindControl() returns null on FormView until call DataBind() .
那么编辑模板必须可见才能让 FindControl 工作。您可能必须使用
OnModeChanged
事件来检查编辑模式,然后找到 DropDownList。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.