C#之DataGridView控件的灵活运用

来源:互联网 发布:网络印刷网站 编辑:程序博客网 时间:2024/06/05 17:57
  以C#中,其控件的灵活动用很重要。在此,简要谈谈DataGridView控件,当在DataGridView控件中验证数据输入功能主要是利用DataGridView控件的公共事件CellValidatingCellEndEdit事件在为当前选定的单元格停止编辑模式时发生。本实例判断控件第一列中单元格的值是否为空。在CellValidating事件中进行验证,如果严重失败,将System.Windows.Forms.DataGridViewCellValidatingEventArgs类的Cancel属性设置为True。这将导致DataGridView控件阻止光标离开该单元格。将该行的ErrorText属性设置为解释性字符串,将显示错误图标,其工具提示将保护此错误文本。在CellEndEdit事件处理程序中,将该行的ErrorText属性设置为空字符串。只有当单元格退出编辑模式(如果验证失败,则不能退出单元格)时,才能发生CellEndEdit事件。运动程序,编辑控件的第一列,在单元格中不输入内容,然后使用鼠标单击其他单元格,这样就会提示错误

下面小编给出大家主要代码:

 

Private void dataGridView1_CellValidating(object sender,DataGridViewCellValidatingEventArgs e)

 {

   If (e.ColumnIndex==0)

     {

         If(String.IsNullOrEmpty(e.FormattedValue.ToString))

         {

           dataGridView1.Rows[e.RowIndex].ErrorText=”单元格第一列值不能为空

           e.Cancel=true;

         }

     }

}

Private void dataGridView1_CellEndEdit(object sender,DataGridViewCellEventArgs e)

{

      dataGridView1.Rows[e.RowIndex].ErrorText=String.Empty;

}

原创粉丝点击