检查C#中的列表是否为空

时间:2013-09-18 08:20:15

标签: c# list gridview isnullorempty

我有一个从数据库填充的对象列表。如果列表为空,我需要显示错误消息,否则显示网格视图。

如何在C#中检查List<T>是否为空?

8 个答案:

答案 0 :(得分:102)

为什么不......

bool isEmpty = !list.Any();
if(isEmpty)
{
    // error message
}
else
{
    // show grid
}

如果数据源为空,GridView也会显示EmptyDataTemplate。这是ASP.NET中的一种方法:

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

<emptydatatemplate>

  <asp:image id="NoDataErrorImg"
    imageurl="~/images/NoDataError.jpg" runat="server"/>

    No Data Found!  

</emptydatatemplate> 

答案 1 :(得分:59)

如果您使用的列表实现是IEnumerable<T>而Linq是一个选项,则可以使用Any

if (!list.Any()) {

}

否则,您通常分别在数组和集合类型上具有LengthCount属性。

答案 2 :(得分:21)

    If (list.Count==0){
      //you can show your error messages here
    } else {
      //here comes your datagridview databind 
    }

您可以使您的数据网格显示为false,并使其在else部分显示。

答案 3 :(得分:12)

使用Count()方法怎么样。

 if(listOfObjects.Count() != 0)
 {
     ShowGrid();
     HideError();
 }
 else
 {
     HideGrid();
     ShowError();
 }

答案 4 :(得分:8)

您应该使用简单的IF声明

List<String> data = GetData();

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

PopulateGrid();
ShowGrid();

答案 5 :(得分:6)

var dataSource = lst!=null && lst.Any() ? lst : null;
// bind dataSource to gird source

答案 6 :(得分:3)

gridview本身有一个方法,用于检查绑定它的数据源是否为空,它允许您显示其他内容。

答案 7 :(得分:0)

如果您使用的是gridview,请使用空数据模板: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>
相关问题