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#?
Why not...
bool isEmpty = !list.Any();
if(isEmpty)
{
// error message
}
else
{
// show grid
}
The GridView
has also an EmptyDataTemplate
which is shown if the datasource is empty. This is an approach in ASP.NET:
<emptydatarowstyle backcolor="LightBlue" forecolor="Red"/>
<emptydatatemplate>
<asp:image id="NoDataErrorImg"
imageurl="~/images/NoDataError.jpg" runat="server"/>
No Data Found!
</emptydatatemplate>
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.
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.
What about using the Count() method.
if(listOfObjects.Count() != 0)
{
ShowGrid();
HideError();
}
else
{
HideGrid();
ShowError();
}
You should use a simple IF
statement
List<String> data = GetData();
if (data.Count == 0)
throw new Exception("Data Empty!");
PopulateGrid();
ShowGrid();
var dataSource = lst!=null && lst.Any() ? lst : null;
// bind dataSource to gird source
gridview itself has a method that checks if the datasource you are binding it to is empty, it lets you display something else.
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>
来源:https://stackoverflow.com/questions/18867180/check-if-list-is-empty-in-c-sharp