Shortcut for (e.Item.ItemType==ListItemType.Item | e.Item.ItemType==ListItemType.AlternatingItem)
Question
When using a DataGrid in ASP.Net is there really no shortcut method for
(e.Item.ItemType==ListItemType.Item || e.Item.ItemType==ListItemType.AlternatingItem)
Basically, "item is an item not a header, footer, separator".
I haven't been able to find one, but I figured I'd put it up to StackOverflow to see if I'm missing one.
Solution
You can create your own Extension Method for this:
using System.Web.UI.WebControls;
public static class UiControlsHelper
{
public static bool IsItem(this DataGridItem item)
{
return item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem;
}
}
Then you can use it like this:
e.Item.IsItem();
Here's the same for the GridView:
public static bool IsDataRow(this GridViewRow row)
{
return row.RowType == DataControlRowType.DataRow;
}
OTHER TIPS
Sagi added an answer to one one my questions.
You can replace:
if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType...
with
if (e.Item.DataItem != null) ...
His answer, not mine. i've not tested it. i don't know if it's:
- valid
- documented
- supported
- subject to change in future versions of .NET framework
There very well may be a situation where the DataItem is assigned, but it's not a valid item. i'll leave it to others to test, up/down vote, and comment.
Not a short cut, but encapsulate that into a function, and your code will be much more readable.
Would be a handy place to make an extension method methinks . . .