zoukankan      html  css  js  c++  java
  • C#获取DataGirdView选定子项子控件类型,is,as的用法

    问题:一个DataGridView中,有的项是编辑控件,有的是下拉控件,想让鼠标点击下拉控件那一项的时候直接展开下拉列表。

    在DataGridView中,动态进行绑定子控件,然后要在CellMouseClick中获取改控件,然后让其展开。

    1 DataGridViewComboBoxCell dgvCombobox = datagridview1.Rows[e.RowIndex].Cell[1] as DataGridViewComboBoxCell;
    2 if(dgvCombobox != null)
    3 {
    4   //执行代码  
    5 }

    关于as的用法:

      as运算符用于在兼容引用类型之间执行某些类型的转换。

    从datagridview中获取的子控件列表是DataGirdViewCellCollection的集合,控件类型是DataGridViewCell类型,而DataGridViewComboBoxCell是继承自该类。

    /**********************Copy自官方手册*******************

    System.Object 
      System.Windows.Forms.DataGridViewElement
        System.Windows.Forms.DataGridViewCell
          System.Windows.Forms.DataGridViewComboBoxCell
    ******************************************************/
    就是可以从基类转换成继承类。as是引用类型转换或者装箱转换,不能用于值转换。
     
    关于is的用法:
      判断兼容性,返回兼容结果true或者false,就是能不能强转的问题。
    if(datagridview1.Rows[e.RowIndex].Cell[1] is DataGridViewComboBoxCell)
    {
        DataGridViewComboBoxCell dgvCombobox = (DataGridViewComboBoxCell)datagridview1.Rows[e.RowIndex].Cell[1];
    //执行代码
    }

    用is会执行两次兼容检查(判断一次,强转一次),性能消耗多一点,所以用as更好一点。直接根据返回结果来判断。

    目前几个还有疑问: 
        疑问1:关于DataGridView中子控件,如果不知道子控件类型,需要对子控件进行类型判断有什么方法?(上面是知道子控件需要的是DataGridViewComboBoxCell)
        疑问2:DataGridViewComboBoxCell类型子项怎么用代码展开,类似树节点的Expand。
        
  • 相关阅读:
    UGUI优化干货总结
    C#合成解析XML与JSON
    镜头跟随玩家移动
    Unity 5 Skybox 旋转
    多线程实现资源下载
    自定义配置文件的使用及加载-txt
    linux下mysql主从复制搭建
    常用模块-正则re
    Elasticsearch分布式搜索
    redis主从复制原理与优化-高可用
  • 原文地址:https://www.cnblogs.com/Iamsorry/p/4748067.html
Copyright © 2011-2022 走看看