如果 ListView 中没有显示任何项目,如何禁用按钮

How to disable a button if no items displayed in a ListView

我创建了一个学生注册向导,他们每年都会使用该向导使用 MultiView 控件,并且我在其中有多个 View 控件。下面是一个 View 控件的示例;

<asp:View ID="address_view" runat="server">
    <h1>Address:</h1>
<asp:Button ID="add_new_address" CssClass="blue" runat="server" Text="Add New Address" OnClick="add_new_address_Click" />
<div id="add_address_div" runat="server">
    <asp:DropDownList ID="address_dropdown_insert" runat="server">
                <asp:ListItem Value="Home">Home Address</asp:ListItem>
                <asp:ListItem Value="Term">Term Time Address</asp:ListItem>
                <asp:ListItem Value="Mail">Mail Address</asp:ListItem>
                <asp:ListItem Value="Business">Business Address</asp:ListItem>
            </asp:DropDownList><br />
            Address 1:
            <asp:TextBox Text="" runat="server" ID="address_1TextBox" /><br />
            Address 2:
            <asp:TextBox Text="" runat="server" ID="address_2TextBox" /><br />
            Town/City:
            <asp:TextBox Text="" runat="server" ID="town_cityTextBox" /><br />
            County:
            <asp:TextBox Text="" runat="server" ID="countyTextBox" /><br />
            PostCode:
            <asp:TextBox Text="" runat="server" ID="postcodeTextBox" /><br />
            Country:
            <asp:TextBox Text="" runat="server" ID="countryTextBox" />
            <asp:Button runat="server" CommandName="Insert" Text="Insert" ID="InsertButton" OnClick="insert_address_button_Click" />
            <asp:Button runat="server" CommandName="Cancel" Text="Clear" ID="Button4" OnClick="cancel_address_button_Click" /><br />
</div>
    <asp:ListView ID="address_list" runat="server" DataSourceID="user_address" DataKeyNames="address_id">
        <EditItemTemplate>
            // code here
        </EditItemTemplate>
        <EmptyDataTemplate>
            <br />
            <p>There are currently no addresses found, please click the button above to add a new address.</p>
        </EmptyDataTemplate>
        <ItemTemplate>
            //code here
        </ItemTemplate>
        <LayoutTemplate>
            //code here
        </LayoutTemplate>
    </asp:ListView>

<br />
    <asp:Button CommandName="NextView" ID="Button1" Enabled="false" runat="server" Text="Next" />
</asp:View>

我在 PageLoad

上有以下 C#
protected void Page_Load(object sender, EventArgs e)
    {
        Button1.Enabled = address_list.Items.Any();
    }

但是,即使ListView 中没有数据,该按钮仍然会出现。 我的问题是,如果用户在 ListView 中没有数据,我如何阻止用户在单击 Button1 时继续进入下一个视图?

我是 C# 的新手,因此非常感谢任何帮助。

试试这样的东西:

if(address_list.Items.Count() = 0)
{
Button1.enabled = false
}else
 {
 Button1.enabled = true
 }

但请记住,如果您在绑定数据之前调用它,它将不起作用,因此请确保不要将此代码用作页面加载事件的第一行

The lv.items.Count() will return 0 if it has no rows after binded