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

时间:2015-11-17 23:11:40

标签: c# asp.net webforms

我创建了一个学生注册向导,每年都会使用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#很新,所以任何帮助都会非常感激。

1 个答案:

答案 0 :(得分:0)

尝试类似:

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

但请记住,如果在绑定数据之前调用它,它就不会工作,所以请确保不要将此代码用作Page load事件中的第一行

  

如果绑定后没有行,则lv.items.Count()将返回0