Check if list is empty in C# [closed]

2019-01-22 05:08发布

I have a list of objects populated from a database. I need to display an error message if the list is empty and display a grid view otherwise.

How do I check if a List<T> is empty in C#?

8条回答
ゆ 、 Hurt°
2楼-- · 2019-01-22 05:36
    If (list.Count==0){
      //you can show your error messages here
    } else {
      //here comes your datagridview databind 
    }

You can make your datagrid visible false and make it visible on the else section.

查看更多
Bombasti
3楼-- · 2019-01-22 05:36

What about using the Count() method.

 if(listOfObjects.Count() != 0)
 {
     ShowGrid();
     HideError();
 }
 else
 {
     HideGrid();
     ShowError();
 }
查看更多
Bombasti
4楼-- · 2019-01-22 05:41

If the list implementation you're using is IEnumerable<T> and Linq is an option, you can use Any:

if (!list.Any()) {

}

Otherwise you generally have a Length or Count property on arrays and collection types respectively.

查看更多
我想做一个坏孩纸
5楼-- · 2019-01-22 05:41

You should use a simple IF statement

List<String> data = GetData();

if (data.Count == 0)
    throw new Exception("Data Empty!");

PopulateGrid();
ShowGrid();
查看更多
一纸荒年 Trace。
6楼-- · 2019-01-22 05:45

gridview itself has a method that checks if the datasource you are binding it to is empty, it lets you display something else.

查看更多
▲ chillily
7楼-- · 2019-01-22 05:50

If you're using a gridview then use the empty data template: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.emptydatatemplate.aspx

      <asp:gridview id="CustomersGridView" 
        datasourceid="CustomersSqlDataSource" 
        autogeneratecolumns="true"
        runat="server">

        <emptydatarowstyle backcolor="LightBlue"
          forecolor="Red"/>

        <emptydatatemplate>

          <asp:image id="NoDataImage"
            imageurl="~/images/Image.jpg"
            alternatetext="No Image" 
            runat="server"/>

            No Data Found.  

        </emptydatatemplate> 

      </asp:gridview>
查看更多
登录 后发表回答