【问题标题】:How to find the DataListItem item type without using FindControl?如何在不使用 FindControl 的情况下查找 DataListItem 项类型?
【发布时间】:2013-09-10 21:33:58
【问题描述】:

我希望能够在后面的 C# 代码中确定我的 DataListItem 类型是否属于 RadioButton 类型。

这可能吗?

如果不是类型 DropDownList 也可以。

有没有办法进行某种检查,例如

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

【问题讨论】:

    标签: asp.net iteration datalistitem


    【解决方案1】:

    item.ItemType 是一个枚举。类型永远不会是 HtmlInputRadioButton

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

    相反,代码应该是这样的——

    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;
        }
    }
    

    【讨论】:

      【解决方案2】:

      最好的选择是:

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

      或者,您可以使用清除器

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

      但这会导致两次强制转换,效率较低。

      【讨论】:

      • 我认为我的问题再次是我在 Web 控件中。它没有解决。
      • 好的,我真的很想避免使用 findcontrol.. 我可能会切换到 jQuery 来验证测验.. 如果这是必须的。
      • @JoJo 您对使用 FindControl 有什么疑虑?
      猜你喜欢
      • 2018-07-08
      • 2020-09-03
      • 1970-01-01
      • 2017-12-10
      • 2013-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多