免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 5129 | 回复: 0
打印 上一主题 下一主题

DataGridView 经典用法总结 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2010-12-01 02:02 |只看该作者 |倒序浏览

一、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.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.Cells[k] = dgcell;

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

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

您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP