做项目时用到了DetailsView控件,在EditItemTemplate中需要自己初始一个DropDownList的数据。我曾尝试在DetailsView控件的ModeChanging或ModeChanged事件中使用FindControl方法来获取目标控件的访问,但是都失败了。
1 <asp:DetailsView ID="DetailsView1" DataKeyNames="ClassID"
2 runat="server" DataSourceID="SqlDataSource1" AutoGenerateRows="False" >
3 <Fields>
4 <asp:BoundField HeaderText="分类名称" DataField="ClassTitle" />
5 <asp:TemplateField HeaderText="所属分类">
6 <ItemTemplate>
7 <%#Eval("ParentTitle") %>
8 </ItemTemplate>
9 <EditItemTemplate>
10 <asp:DropDownList ID="ddlParent" runat="server" onDataBinding="ddlParent_DataBinding">
11 </asp:DropDownList>
12 </EditItemTemplate>
13 </asp:TemplateField>
14 <asp:CommandField ShowEditButton="True" />
15 </Fields>
16 </asp:DetailsView>
cs文件中:
1 protected void ddlParent_DataBinding(object sender, EventArgs e)
2 {
3 //添加数据绑定代码
4 //BindDropDownList((DropDownList)sender);
5 }
注意:
失败是因为调用FindControl方法太早了,你得在DetailsView的ItemCreated事件或者是PreRender事件里做才行。
protected void DetailsView1_PreRender(object sender, EventArgs e)
{
if (IsPostBack)
{
DetailsView detailsView = (DetailsView)sender;
if (detailsView.CurrentMode == DetailsViewMode.Edit)
{
DropDownList dropDownList = (DropDownList)detailsView.FindControl("DropDownList1");
dropDownList.Items.Add(new ListItem("text", "value"));
}
}
}
我是利用DropDownList_DataBinding事件来解决,给在DetailsView控件TemplateField中的DropDownList加上onDataBinding事件命令。然后在cs中处理这个事件就OK了。
DetailsView的aspx中代码如下(省略数据源代码):
1 <asp:DetailsView ID="DetailsView1" DataKeyNames="ClassID"
2 runat="server" DataSourceID="SqlDataSource1" AutoGenerateRows="False" >
3 <Fields>
4 <asp:BoundField HeaderText="分类名称" DataField="ClassTitle" />
5 <asp:TemplateField HeaderText="所属分类">
6 <ItemTemplate>
7 <%#Eval("ParentTitle") %>
8 </ItemTemplate>
9 <EditItemTemplate>
10 <asp:DropDownList ID="ddlParent" runat="server" onDataBinding="ddlParent_DataBinding">
11 </asp:DropDownList>
12 </EditItemTemplate>
13 </asp:TemplateField>
14 <asp:CommandField ShowEditButton="True" />
15 </Fields>
16 </asp:DetailsView>
cs文件中:
1 protected void ddlParent_DataBinding(object sender, EventArgs e)
2 {
3 //添加数据绑定代码
4 //BindDropDownList((DropDownList)sender);
5 }
注意:
失败是因为调用FindControl方法太早了,你得在DetailsView的ItemCreated事件或者是PreRender事件里做才行。
protected void DetailsView1_PreRender(object sender, EventArgs e)
{
if (IsPostBack)
{
DetailsView detailsView = (DetailsView)sender;
if (detailsView.CurrentMode == DetailsViewMode.Edit)
{
DropDownList dropDownList = (DropDownList)detailsView.FindControl("DropDownList1");
dropDownList.Items.Add(new ListItem("text", "value"));
}
}
}
本文转自钢钢博客园博客,原文链接http://www.cnblogs.com/xugang/archive/2007/07/10/812515.html,如需转载请自行联系原作者