我有这个标记:
<asp:DetailsView ID="dvDatabase" OnModeChanging="dvDatabase_ModeChanging">
<HeaderTemplate>
<asp:Button ID="btnView" runat="server" CausesValidation="False" CommandName="Cancel"
Text="View" CssClass="btn btn-primary" Visible="false" />
<asp:Button runat="server" CausesValidation="False" CommandName="Edit"
Text="Edit" CssClass="btn btn-success" ID="btnEdit" />
<asp:Button runat="server" CausesValidation="False" CommandName="Delete"
Text="Delete" CssClass="btn btn-danger" />
</HeaderTemplate>
...
然后我有了这个C#:
protected void dvDatabase_ModeChanging(object sender, DetailsViewModeEventArgs e)
{
bool isEdit = DetailsViewMode.Edit == e.NewMode;
DetailsView view = (DetailsView)sender;
Button viewButton = (Button)view.FindControl("btnView");
Button editButton = (Button)view.FindControl("btnEdit");
viewButton.Visible = isEdit;
editButton.Visible = !isEdit;
}
我已完成一些调试并且Visible
属性设置正确,但我从未看到按钮发生变化。我点击编辑按钮,我处于编辑模式,但仍然显示编辑按钮,仍然隐藏视图按钮。我已尝试直接通过dvDatabase.FindControl
找到按钮,而不是使用object sender
变量,但这也不起作用。我尝试根据标记中的ID
属性引用带变量的按钮,但btnView
和btnEdit
变量/属性不存在。发生了什么事?
修改:根据蒂姆的建议我切换到OnModeChanged
,但按钮仍然没有改变。这是我现在的C#:
protected void dvDatabase_ModeChanged(object sender, EventArgs e)
{
DetailsView view = /*(DetailsView)sender*/dvDatabase;
bool isEdit = DetailsViewMode.Edit == view.CurrentMode;
LinkButton viewButton = (LinkButton)view.FindControl("btnView");
LinkButton editButton = (LinkButton)view.FindControl("btnEdit");
viewButton.Visible = isEdit;
editButton.Visible = !isEdit;
}
我尝试使用object sender
以及dvDatabase
类变量,但似乎都没有效果。
答案 0 :(得分:2)
改为使用DetailsView
的{{3}}事件,并仅对DetailsView if(!Page.IsPostback)
进行数据绑定。您还需要处理DataBound
事件以调用相应的ItemCommand
并数据绑定DetailsView
。
protected void dvDatabase_DataBound(Object sender, EventArgs e)
{
var view = (DetailsView)sender;
var btnView = (Button)view.FindControl("btnView");
var btnEdit = (Button)view.FindControl("btnEdit");
switch (view.CurrentMode)
{
case DetailsViewMode.ReadOnly:
btnView.Visible = false;
btnEdit.Visible = true;
break;
case DetailsViewMode.Edit:
btnView.Visible = true;
btnEdit.Visible = false;
break;
case DetailsViewMode.Insert:
btnView.Visible = false;
btnEdit.Visible = false;
break;
default:
break;
}
}