zoukankan      html  css  js  c++  java
  • DataGridView 经典用法总结(上)附有可下载的Demo

    一、DataGridView 单元格验证

     

    比如只允许输入数字

    要求:验证错误后焦点不离开。

     

    有两种方法:

    DataGridView.EditingControlShowing 事件和DataGridView.CellValidating 事件。

    (1) DataGridView.EditingControlShowing 事件。

    显示用于编辑单元格的控件时发生,命名空间: System.Windows.Forms

    程序集: System.Windows.Forms(在 system.windows.forms.dll 中)。

    如:

    void dgvCs_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)

            {

                e.CellStyle.BackColor = Color.Aquamarine;//设置编译时的颜色

                control = new TextBox();

                control = (TextBox)e.Control;

                control.KeyPress += new KeyPressEventHandler(txt_KeyPress);//

            }

    然后在txt_KeyPress这里进行验证。

     

     

    (2) DataGridView.CellValidating 事件。

    在单元格失去输入焦点时发生,并启用内容验证功能。命名空间: System.Windows.Form,程序集: System.Windows.Forms(在 System.Windows

    .Forms.dll 中)

    备注:

    验证不通过时调用e.Cancel = true,终止事件链,单元格将保持编辑状态。

    调用dgv_details.CancelEdit();可以使单元格的内容会滚到修改前的值。

    使用System.Windows.Forms.SendKeys.Send("^a");将全选单元格的内容。

    如: 

    void dgv_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)

            {

                    decimal tmp = 0.0m;

                    if (!decimal.TryParse(e.FormattedValue.ToString(), out tmp))//是否是数字

                    {

                        if (e.FormattedValue != null && e.FormattedValue.ToString().Length != 0)

                        {

                           DevComponents.DotNetBar.MessageBoxEx.Show("请输入有效数字!", "提示");

                           e.Cancel = true;

                        }

                    }

             }

    这两种方法都能验证。第一种方法当按键按下时(即当编译时)就去验证,而第二种方法是当焦点离开单元格编译区域时触发。所以个人感觉第一种方法更优一点。

     

    二、指定选中单元格并开始编辑状态

     

    实现:

    //获得焦点

    DataGridView.Focus();

    //指定当前单元格

    DataGridView.CurrentCell = dgv_details[0, 0]; []中对应参数为列索引(或列标题)、行索引。(注意:不是默认的先行索引)

    //开始编辑状态

    d DataGridView.BeginEdit(false);false是指对指定行进行编辑。

    DataGridView.BeginEdit 方法 尝试将网格置于允许编辑的状态。

     

    命名空间: System.Windows.Forms

    程序集: System.Windows.Forms(在 System.Windows.Forms.dll 中)

     

    三、在拖动列的滚动条时可以将指定的列冻结。

     

    this.dataGridView1.Columns["AddToCartButton"].Frozen = true;

    说明:中括号([])中指相应列的索引或者相应列的标题

    这个知道了后一看就应该明白,无需多加解释。

     

     

    四、 DataGridView选择的部分拷贝至剪贴板 。

     

    拷贝模式设定

     

    DataGridView1.ClipboardCopyMode= DataGridViewClipboardCopyMode.EnableWithoutHeaderText //设置可复制的模式

     

    其中DataGridView.ClipboardCopyMode 属性获取或设置一个值,该值指示用户是否可以将单元格的文本值复制到 Clipboard,以及是否包括行标题和列标题文本。

     

    命名空间: System.Windows.Forms

    程序集: System.Windows.Forms(在 System.Windows.Forms.dll 中)

     

    选中部分拷贝

     

    Clipboard.SetDataObject(DataGridView1.GetClipboardContent()) //将控件选中的数据置于系统剪贴板中

     

    DataGridView粘贴

     

    代码

    if (DataGridView1.CurrentCell.Value == null)

    {

        return;

    }

    int insertRowIndex = DataGridView1.CurrentCell.RowIndex;

    string pasteText=Clipboard.GetText();//从系统剪贴板中获取数据

    if(string.IsNullOrEmpty(pasteText))

    {

        return;

    }

    string[] lines=pasteText.Split('\r');//按行分组

    bool isHeader=true;

    foreach(string line in lines)

    {   

        if(isHeader)

        {

            isHeader=false;//当可复制模式中含有标题时的过滤操作

        }

        else

        {

            string[] vals=line.Split('\t');//按tab空格分组

            if (vals.Length - 1 != DataGridView1.ColumnCount)

            {

                throw new ApplicationException("列数错误");

            }

            DataGridViewRow row = DataGridView1.Rows[insertRowIndex];

            row.HeaderCell.Value=vals[0];

            for(int i=0;i<row.Cells.Count-1;i++)

            {

                row.Cells[i].Value=vals[(i+1)];

            }

            insertRowIndex+=1;

        }

    }

     

     

    五、DatagridView自动编号

     

    代码

     private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)

            {

                   //自动编号与数据库无关

                Rectangle rectangle = new Rectangle(e.RowBounds.Location.X, e.RowBounds.Location.Y

    ,dataGridView1.RowHeadersWidth - 4,e.RowBounds.Height);

     

                TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(),dataGridView1.

    RowHeadersDefaultCellStyle.Font, rectangle,

                dataGridView1.RowHeadersDefaultCellStyle.ForeColor, TextFormatFlags.VerticalCenter | TextFormatFlags.Right);

            }

     

    显示行号

     

     

    六、 指定单元格属性

     

     

    DataGridViewCell dgcell = new DataGridViewTextBoxCell();//申明单元格类型

     this.dgvCss.Rows[i].Cells[k] = dgcell;

    其实很简单,只是很多人不知道有这个属性。但这种方式和带有复选框类型的单元格使用时,一般情况下出错,也给一些人一种错觉以为单元格类型不能这么操作。其实是因为你在申明列的时候先申明的checkbox类型的,而这时他们便有一个默认值(FormattedValue)false,当你重新给他赋值单元格类型时便会出现FormattedValue错误,这时你只需给它一个默认值就可以,如

    this.dgvCss.Rows[i].Cells[k].Value = ""; 这样便可解决。

     

    部分代码Demo   其中Demo中有部分是(中)、(下)的内容

     

    转载请注明出处!

    欢迎大家讨论:如有疑问请联系elivn@vip.qq.com

  • 相关阅读:
    Spring 中的事务操作、注解、以及 XML 配置
    ..OBJLED.axf: Error: L6218E: Undefined symbol EXTI_Init (referred from exti.o). 错误修改
    ADC分辨率
    单片机ADC检测4-20mA电路,以及计算方法
    STM32速度---网页讲解
    转载电子发烧友网---STM32的IO口灌入电流和输出驱动电流
    精密电阻性能
    ..OBJCAN.axf: Error: L6411E: No compatible library exists with a definition of startup symbol __main.
    asp.net---jquery--ajax 实现滚动条滚动到底部分页显示
    柱状图dataLabels 文字格式 以及如何获取柱子的name(名称)属性
  • 原文地址:https://www.cnblogs.com/elivn/p/1892247.html
Copyright © 2011-2022 走看看