• 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。
        
  • 相关阅读:
    【Mesh R-CNN】论文翻译(原理部分)
    关于栈的学习记录
    css入门笔记
    前端学习之html基础知识归纳
    navigator url无法跳转跳转问题
    新手小白学会vim脚本配置
    Linux下实现两个变量之间传参
    [Apache Doris] Apache Doris 架构及代码目录解读
    [编程总结] 开源系统平台化建设思路
    论文阅读|PointRend: Image Segmentation as Rendering
  • 原文地址:https://www.cnblogs.com/Iamsorry/p/4748067.html
Copyright © 2020-2023  润新知