我有一个列表视图加载页面,但我想隐藏一个带条件的按钮。
我收到此错误消息 对象引用未设置为对象的实例。
甚至认为commandName有一个值。代码在listview数据绑定下。
这是我的代码:
protected void PostListView_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item == null)
return;
MembershipUser currentUser = Membership.GetUser();
Guid currentUserId = (Guid)currentUser.ProviderUserKey;
Button btn1 = (Button)e.Item.FindControl("deleteButton");
if (currentUserId.ToString() == btn1.CommandName.ToString())
{
Button hdn = (Button)e.Item.FindControl("deleteButton");
btn1.Visible = false;
}
else
{
Button hdn = (Button)e.Item.FindControl("deleteButton");
btn1.Visible = false;
}
}
<asp:ListView ID="PostListView" runat="server" DataSourceID="POSTDataSource2" OnItemDataBound="PostListView_ItemDataBound" OnLoad="PostListView_Load">
<AlternatingItemTemplate>
<p class="text-muted">
<asp:Button ID="deleteButton" runat="server" Text="Delete" CssClass="btn btn-info btn-xs pull-right" Width="50px" CommandName='<%# Eval("UserId") %>' />
</p>
</AlternatingItemTemplate>
答案 0 :(得分:0)
您必须查看ItemDataBound
中的ItemType
:
protected void PostListView_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
MembershipUser currentUser = Membership.GetUser();
Guid currentUserId = (Guid)currentUser.ProviderUserKey;
Button btn1 = (Button)e.Item.FindControl("deleteButton");
if (currentUserId.ToString() == btn1.CommandName.ToString())
{
Button hdn = (Button)e.Item.FindControl("deleteButton");
btn1.Visible = false;
}
else
{
Button hdn = (Button)e.Item.FindControl("deleteButton");
btn1.Visible = false;
}
}
}