DataGridView知识点.doc_第1页
DataGridView知识点.doc_第2页
DataGridView知识点.doc_第3页
DataGridView知识点.doc_第4页
DataGridView知识点.doc_第5页
已阅读5页,还剩10页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

第24课 Ado.Net技术(下)DataGridView知识点一、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_details0, 0; 中对应参数为列索引(或列标题)、行索引。(注意:不是默认的先行索引)/开始编辑状态 d DataGridView.BeginEdit(false);false是指对指定行进行编辑。DataGridView.BeginEdit 方法 尝试将网格置于允许编辑的状态。命名空间:System.Windows.Forms程序集:System.Windows.Forms(在 System.Windows.Forms.dll 中)三、在拖动列的滚动条时可以将指定的列冻结。this.dataGridView1.ColumnsAddToCartButton.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.RowsinsertRowIndex; row.HeaderCell.Value=vals0; for(int i=0;irow.Cells.Count-1;i+) row.Cellsi.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.Rowsi.Cellsk = dgcell;其实很简单,只是很多人不知道有这个属性。但这种方式和带有复选框类型的单元格使用时,一般情况下出错,也给一些人一种错觉以为单元格类型不能这么操作。其实是因为你在申明列的时候先申明的checkbox类型的,而这时他们便有一个默认值(FormattedValue)false,当你重新给他赋值单元格类型时便会出现FormattedValue错误,这时你只需给它一个默认值就可以,如this.dgvCss.Rowsi.Cellsk.Value = ; 这样便可解决。知识点:一:DatagridView 导出数据到Excel(两种方法)二:DatagridView 中显示密码列三:WinForm最简单两GridView同步滚动四:DataGridView添加任何控件一.DatagridView 导出数据到Excel 有两种方法:一种是直接利用I/O读写去生成非标准格式的xls文件,速度很快。另外种就是直接使用EXCEL的COM组件实现,需要在项目中引用EXCEL的COM组件。代码 (1)利用I/O。1privatevoidbutton4_Click(objectsender,EventArgse)234/利用流导出Exce5saveFileDialog.Filter=Execlfiles(*.xls)|*.xls;6saveFileDialog.FileName=mydata;78saveFileDialog.FilterIndex=0;910saveFileDialog.RestoreDirectory=true;1112saveFileDialog.CreatePrompt=true;1314saveFileDialog.Title=ExportExcelFileTo;15saveFileDialog.ShowDialog();16StreammyStream;1718try1920myStream=saveFileDialog.OpenFile();2122catch2324return;252627/StreamWritersw=newStreamWriter(myStream,System.Text.Encoding.GetEncoding(gb2312);28StreamWritersw=newStreamWriter(myStream,System.Text.Encoding.GetEncoding(-0);29stringstr=;30try3132/写标题33for(inti=0;i0)3637str+=t;3839str+=DataGridView1.Columnsi.HeaderText;404142sw.WriteLine(str);43/写内容4445for(intj=0;jDataGridView1.Rows.Count;j+)4647stringtempStr=;4849for(intk=0;k0)5253tempStr+=t;545556tempStr+=DataGridView1.Rowsj.Cellsk.Value.ToString();575859sw.WriteLine(tempStr);606162sw.Close();63myStream.Close();64656667catch(Exceptionex)6869MessageBox.Show(ex.ToString();707172finally7374sw.Close();75myStream.Close();7677/System.Diagnostics.StopwatchswT=newSystem.Diagnostics.Stopwatch();78/swT.Start();79 ts1=swT.ElapsedMilliseconds;80/MessageBox.Show(ts1.ToString()+n);81复制代码(2).利用组件。 首先添加Excel引用实现代码1publicstaticvoidDataGridViewToExcel(stringfileName,DataGridViewmyDGV)23stringsaveFileName=;4/boolfileSaved=false;5SaveFileDialogsaveDialog=newSaveFileDialog();6saveDialog.DefaultExt=xls;7saveDialog.Filter=Excel文件|*.xls;8saveDialog.FileName=fileName;9saveDialog.ShowDialog();10saveFileName=saveDialog.FileName;11if(saveFileName.IndexOf(:)0)return;/被点了取消12Microsoft.Office.Interop.Excel.ApplicationxlApp=newMicrosoft.Office.Interop.Excel.Application();13if(xlApp=null)1415MessageBox.Show(无法创建Excel对象,可能您的机子未安装Excel);16return;171819Microsoft.Office.Interop.Excel.Workbooksworkbooks=xlApp.Workbooks;20Microsoft.Office.Interop.Excel.Workbookworkbook=workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);21Microsoft.Office.Interop.Excel.Worksheetworksheet=(Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets1;/取得sheet12223/写入标题24for(inti=0;imyDGV.ColumnCount;i+)2526worksheet.Cells1,i+1=myDGV.Columnsi.HeaderText;2728/写入数值29for(intr=0;rmyDGV.Rows.Count;r+)3031for(inti=0;imyDGV.ColumnCount;i+)3233worksheet.Cellsr+2,i+1=myDGV.Rowsr.Cellsi.Value;3435System.Windows.Forms.Application.DoEvents();3637worksheet.Columns.EntireColumn.AutoFit();/列宽自适应38/if(Microsoft.Office.Interop.cmbxType.Text!=Notification)39/40/Excel.Rangerg=worksheet.get_Range(worksheet.Cells2,2,worksheet.Cellsds.Tables0.Rows.Count+1,2);41/rg.NumberFormat=00000000;42/4344if(saveFileName!=)4546try4748workbook.Saved=true;49workbook.SaveCopyAs(saveFileName);50/fileSaved=true;5152catch(Exceptionex)5354/fileSaved=false;55MessageBox.Show(导出文件时出错,文件可能正被打开!n+ex.Message);56575859/else60/61/fileSaved=false;62/63xlApp.Quit();64GC.Collect();/强行销毁65/if(fileSaved&System.IO.File.Exists(saveFileName)System.Diagnostics.Process.Start(saveFileName);/打开EXCEL66MessageBox.Show(导出成功,提示,MessageBoxButtons.OK);67复制代码以上两种方法都能实现Excel的导出,根据验证第一种方法的导出效率要比第二种要高很多,至于选择哪种导出方式以及性能的具体对比还需要读者详细的去衡量。二.显示密码列 DataGridView.CellFormatting事件在单元格的内容需要设置格式以便于显示时发生。 命名空间:System.Windows.Forms程序集:System.Windows.Forms(在 system.windows.forms.dll 中)如:代码 /单元格显示格式事件/privatevoiddataGridView1_CellFormatting(objectsender,DataGridViewCellFormattingEventArgse)/把第4列显示*号,*号的个数和实际数据的长度相同if(e.ColumnIndex=3)if(e.Value!=null&e.Value.ToString().Length0)e.Value=newstring(*,e.Value.ToString().Length);复制代码DataGridView.EditingControlShowing 事件在显示用于编辑单元格的控件时发生。 命名空间: System.Windows.Forms程序集: System.Windows.Forms(在 system.windows.forms.dll 中)1/23/编辑单元格控件事件45/67/89/1011privatevoiddataGridView1_EditingControlShowing(objectsender,1213DataGridViewEditingControlShowingEventArgse)14151617/编辑第4列时,把第4列显示为*号1819TextBoxt=e.ControlasTextBox;2021if(t!=null)22232425if(this.dataGridView1.CurrentCell.ColumnIndex=3)2627t.PasswordChar=*;2829else3031t.PasswordChar=newchar();3233343536复制代码三.WinForm最简单两GridView同步滚动 DataGridView. Scroll网格水平滚动或垂直滚动引发的事件。如何让两个DataGridView保持同步滚动? 一个最简单方法: 不过大数据量时界面会闪。代码 privatevoidDataGridView1_Scroll(objectsender,ScrollEventArgse)dataGridView2.FirstDisplayed

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论