




版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1、第24课 Ado.Net技术(下)DataGridView知识点一、DataGridView 单元格验证 比如只允许输入数字 要求:验证错误后焦点不离开。 有两种方法:DataGridView.EditingControlShowing 事件和DataGridView.CellValidating 事件。(1) DataGridView.EditingControlShowing 事件。程序集: System.Windows.Forms(在 system.windows.forms.dll 中)。如:void dgvCs_EditingControlShowing
2、(object sender, DataGridViewEditingControlShowingEventArgs e) e.CellStyle.BackColor = Color.Aquamarine;/设置编译时的颜色 control = ne
3、w TextBox(); control = (TextBox)e.Control; control.KeyPress += new KeyPressEventHandler(txt_KeyPress);/ 然后在txt_KeyPress这里进行验证。
4、 (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"
5、;);将全选单元格的内容。如: void dgv_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) decimal tmp = 0.0m; &
6、#160; if (!decimal.TryParse(e.FormattedValue.ToString(), out tmp)/是否是数字
7、 if (e.FormattedValue != null && e.FormattedValue.ToString().Length != 0)
8、160; DevComponents.DotNetBar.MessageBoxEx.Show("请输入有效数字!", "提示"); e.Cancel = true;
9、 这两种方法都能验证。第一种方法当按键按下时(即当编译时)就去验证,而第二种方法是当焦点离开单元格编译区域时触发。所以个人感觉第一种方法更优一点。
10、60;二、指定选中单元格并开始编辑状态 实现:/获得焦点 DataGridView.Focus(); /指定当前单元格 DataGridView.CurrentCell = dgv_details0, 0; 中对应参数为列索引(或列标题)、行索引。(注意:不是默认的先行索引)/开始编辑状态 d DataGridView.BeginEdit(false);false是指对指定行进行编辑。DataGridView.BeginEdit 方法 尝试将网格置于允许编辑的状态。 命名空间: 程序集: System.Windows.Forms(在 System.Win
11、dows.Forms.dll 中) 三、在拖动列的滚动条时可以将指定的列冻结。 this.dataGridView1.Columns"AddToCartButton".Frozen = true;说明:中括号()中指相应列的索引或者相应列的标题这个知道了后一看就应该明白,无需多加解释。 四、 DataGridView选择的部分拷贝至剪贴板 。 拷贝模式设定 DataGridView1.ClipboardCopyMode= DataGridViewClipboardCopyMode.EnableWithoutHe
12、aderText /设置可复制的模式 其中DataGridView.ClipboardCopyMode 属性获取或设置一个值,该值指示用户是否可以将单元格的文本值复制到 Clipboard,以及是否包括行标题和列标题文本。 命名空间: 程序集: System.Windows.Forms(在 System.Windows.Forms.dll 中) 选中部分拷贝 Clipboard.SetDataObject(DataGridView1.GetClipboardContent() /将控件选中的数据置于系统剪贴板中 DataG
13、ridView粘贴 代码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');/按行分组b
14、ool isHeader=true;foreach(string line in lines) if(isHeader) isHeader=false;/当可复制模式中含有标题时的过滤操作 else stri
15、ng vals=line.Split('t');/按tab空格分组 if (vals.Length - 1 != DataGridView1.ColumnCount) throw new ApplicationException("列数错误");
16、160; DataGridViewRow row = DataGridView1.RowsinsertRowIndex; row.HeaderCell.Value=vals0; for(int i=0;i<row.Cells.Count-1;i+)
17、0; row.Cellsi.Value=vals(i+1); insertRowIndex+=1; 五、DatagridView自动编号 代码 private voi
18、d dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e) /自动编号与数据库无关 ,dataGridView1.
19、RowHeadersWidth - 4,e.RowBounds.Height); TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(),dataGridView1.RowHeadersDefaultCellStyle.Font, rectangle, d
20、ataGridView1.RowHeadersDefaultCellStyle.ForeColor, TextFormatFlags.VerticalCenter | TextFormatFlags.Right); 显示行号 六、 指定单元格属性 DataGridViewCell dgcell = new DataGridViewTextBoxCell();/申明单元格类型 this.dgvCss.Rowsi.Cellsk = dgcell;其实
21、很简单,只是很多人不知道有这个属性。但这种方式和带有复选框类型的单元格使用时,一般情况下出错,也给一些人一种错觉以为单元格类型不能这么操作。其实是因为你在申明列的时候先申明的checkbox类型的,而这时他们便有一个默认值(FormattedValue)false,当你重新给他赋值单元格类型时便会出现FormattedValue错误,这时你只需给它一个默认值就可以,如this.dgvCss.Rowsi.Cellsk.Value = "" 这样便可解决。知识点:一:DatagridView 导出数据到Excel(两种方法)二:DatagridView 中显示密码列三:WinF
22、orm最简单两GridView同步滚动四:DataGridView添加任何控件 一.DatagridView 导出数据到Excel 有两种方法:一种是直接利用I/O读写去生成非标准格式的xls文
23、件,速度很快。另外种就是直接使用EXCEL的COM组件实现,需要在项目中引用EXCEL的COM组件。代码 (1)利用I/O。 1 private void button4_Click(object sender, EventArgs e) 2 3 4
24、; /利用流导出Exce 5 saveFileDialog.Filter = "Execl files (*.xls)|*.xls" 6 saveFileDialog.FileName
25、60;= "mydata" 7 8 saveFileDialog.FilterIndex = 0; 9 10 saveFileDialog.RestoreDirectory =
26、160;true;11 12 saveFileDialog.CreatePrompt = true;13 14 saveFileDialog.Title = "Export Excel File
27、0;To"15 saveFileDialog.ShowDialog();16 Stream myStream;17 18
28、; try19 20 myStream = saveFileDialog.OpenFile();21
29、60; 22 catch23 24 return;25&
30、#160; 26 27 /StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding("gb2312");28
31、60; StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0);29 string str = ""30
32、160; try31 32 /写标题33 &
33、#160; for (int i = 0; i < this.DataGridView1.ColumnCount; i+)34 35 &
34、#160; if (i > 0)36 37
35、; str += "t"38 39 &
36、#160; str += DataGridView1.Columnsi.HeaderText;40 41 42
37、0; sw.WriteLine(str);43 /写内容44 45
38、for (int j = 0; j < DataGridView1.Rows.Count; j+)46 47
39、 string tempStr = ""48 49 for (int k = 0; k < DataGridView1.Columns.Count; k+)5
40、0 51 if (k >&
41、#160;0)52 53 &
42、#160; tempStr += "t"54 55 56
43、60; tempStr += DataGridView1.Rowsj.Cellsk.Value.ToString();57 58 59
44、0; sw.WriteLine(tempStr);60 61 62
45、 sw.Close();63 myStream.Close();64 65 66 67
46、0; catch (Exception ex)68 69 MessageBox.Show(ex.ToString();
47、70 71 72 finally73 74 &
48、#160; sw.Close();75 myStream.Close();76 77
49、60; /System.Diagnostics.Stopwatch swT = new System.Diagnostics.Stopwatch();78 /swT.Start();79 ts1 = swT.ElapsedMilliseconds;80
50、160; /MessageBox.Show(ts1.ToString() + "n");81 复制代码 (2).利用组件。 首先添加Excel引用实现代码 1 public s
51、tatic void DataGridViewToExcel(string fileName, DataGridView myDGV) 2 3 string saveFileName = "" 4
52、 /bool fileSaved = false; 5 SaveFileDialog saveDialog = new SaveFileDialog(); 6
53、0; saveDialog.DefaultExt = "xls" 7 saveDialog.Filter = "Excel文件|*.xls" 8
54、 saveDialog.FileName = fileName; 9 saveDialog.ShowDialog();10 saveFileName = saveDialog.FileName;1
55、1 if (saveFileName.IndexOf(":") < 0) return; /被点了取消 12 Microsoft.Office.Interop.Excel.Application
56、xlApp = new Microsoft.Office.Interop.Excel.Application();13 if (xlApp = null)14 15
57、0; MessageBox.Show("无法创建Excel对象,可能您的机子未安装Excel");16 return;17
58、60; 18 19 Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;20 Microsoft.Office.Interop.Excel.Wo
59、rkbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);21 Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)w
60、orkbook.Worksheets1;/取得sheet1 22 23 /写入标题24 for (int i = 0; i < myDGV.ColumnCount; i+)25
61、; 26 worksheet.Cells1, i + 1 = myDGV.Columnsi.HeaderText;27
62、160; 28 /写入数值29 for (int r = 0; r < myDGV.Rows.Count; r+)30
63、60; 31 for (int i = 0; i < myDGV.ColumnCount; i+)32
64、0; 33 worksheet.Cellsr + 2, i + 1 = myDGV.Rowsr.Cellsi.Value;34
65、 35 System.Windows.Forms.Application.DoEvents();36
66、 37 worksheet.Columns.EntireColumn.AutoFit();/列宽自适应38 /if (Microsoft.Office.Interop.cmbxType.Text != "Notification")
67、39 /40 / Excel.Range rg = worksheet.get_Range(worksheet.Cells2, 2, worksheet.Cellsds.Tables0.Rows.
68、Count + 1, 2);41 / rg.NumberFormat = "00000000"42 /43 44
69、60; if (saveFileName != "")45 46 try47
70、 48 workbook.Saved = true;49
71、 workbook.SaveCopyAs(saveFileName);50 /fileSaved = true;51
72、 52 catch (Exception ex)53
73、160; 54 /fileSaved = false;55 Messa
74、geBox.Show("导出文件时出错,文件可能正被打开!n" + ex.Message);56 57 58 59
75、0; /else60 /61 / fileSaved = false;62
76、; /63 xlApp.Quit();64 GC.Collect();/强行销毁 65
77、60; / if (fileSaved && System.IO.File.Exists(saveFileName) System.Diagnostics.Process.Start(saveFileName); /打开EXCEL66 MessageBox.Show("导出成功", "提示",
78、160;MessageBoxButtons.OK);67 复制代码 以上两种方法都能实现Excel的导出,根据验证第一种方法的导出效率要比第二种要高很多,至于选择哪种导出方式以及性能的具体对比还需要读者详细的去衡量。 二.显示密码列 &
79、#160; DataGridView.CellFormatting事件&
80、#160;在单元格的内容需要设置格式以便于显示时发生。 程序集:System.Windows.Forms(在 system.windows.forms.dll 中)如: 代码 / <summary>/ 单元格显示格式事件/ </summary>/ <param name="sender"></param>/ <param name="e"></param>private void da
81、taGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) / 把第4列显示*号,*号的个数和实际数据的长度相同 if (e.ColumnIndex = 3) if (e.Value !
82、= null && e.Value.ToString().Length > 0) e.Value = new string('*',e.Value.ToString().Length);
83、; 复制代码 DataGridView.EditingControlShowing 事件在显示用于编辑单元格的控件时发生。 程序集: System.Windows.Forms(在 system.windows.forms.dll 中) 1 / <summary> 2 3 / 编辑单元格控件事件 4 5 / </summary>
84、;6 7 / <param name="sender"></param> 8 9 / <param name="e"></param>10 11 private void dataGridView1_EditingControlShowing(object sender, 12 13 DataGridViewEdit
85、ingControlShowingEventArgs e)14 15 16 17 / 编辑第4列时,把第4列显示为*号18 19 TextBox t = e.Control as TextBox;20 21 if (t != null)22 23
86、0; 24 25 if (this.dataGridView1.CurrentCell.ColumnIndex = 3)26 27 t.PasswordChar = '*'28 29
87、160; else30 31 t.PasswordChar = new char();32 33 34 35 36 复制代码 三.WinForm最简单两GridView同步滚动 DataGridView. Scroll网格
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 放射师考试题及答案
- 防暑知识考试题及答案
- (正式版)DB15∕T 3672-2024 《设施蔬菜秸秆原位还田技术规程》
- (正式版)DB15∕T 3657-2024 《香菇干燥技术规程》
- 毒贩刑侦考试题及答案
- 项目管理进度报告模板项目风险与资源管理
- (正式版)DB15∕T 3281-2023 《骆驼绒纤维外观形态图谱》
- 知识产权保护宣言及承诺书(9篇)
- 临川护理三基考试题库及答案
- 商业合同审查与修订工作指引
- 地沟更换管线专项施工方案
- 两段炉讲座课件
- 泵送式桥塞与射孔联做技术介绍n课件
- 海南省危房改造对象认定表
- GB/T 8295-2008天然橡胶和胶乳铜含量的测定光度法
- 生产作业管理讲义
- 诗和词的区别课件
- 战现场急救技术教案
- 内蒙古电网介绍
- 气力输送计算
- 公共关系学授课教案
评论
0/150
提交评论