Question

I want to be able to determine if my DataListItem type is of type RadioButton in C# code behind.

Is this possible?

Alternatively if it is not type DropDownList that would also work.

Isn't there a way to some kind of check such as

if(item.ItemType.Equals(HtmlInputRadioButton)){ // }

Was it helpful?

Solution

item.ItemType is an enum. Type will never be HtmlInputRadioButton

  public enum ListItemType
  {
    Header,
    Footer,
    Item,
    AlternatingItem,
    SelectedItem,
    EditItem,
    Separator,
    Pager,
  }

Instead, the code should be like this -

void Item_XXXX(Object sender, DataListItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item ||
        e.Item.ItemType == ListItemType.AlternatingItem)
    {
        // Make sure MyRadioButtonId is an ID of HtmlInputRadioButton
        var htmlInputRadioButton = e.Item.FindControl("MyRadioButtonId") 
          as HtmlInputRadioButton;
    }
}

OTHER TIPS

The best option is:

var radio = item as RadioButton;
if(null != radio)
{
    // It's a radio button!
    // The "as" keyword will return null if the cast fails
}

Alternatively, you can use the clearer

if(item is RadioButton)
{
    var radio = (RadioButton)item;
}

But that results in two casts, which is less efficient.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top