views:

559

answers:

4

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.

+2  A: 

Not a short cut, but encapsulate that into a function, and your code will be much more readable.

Matthew Vines
A: 

Would be a handy place to make an extension method methinks . . .

Wyatt Barnett
+4  A: 

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;
}
MartinHN
This is what I currently have and so far has proven workable. I was looking for something simpler.
Jared
I don't think you can get simpler than that. You just have to ask e.Item.IsItem() in your if, where you had that long screamer before...
MartinHN
+1  A: 

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.

Ian Boyd