DataGridVIew的使用学习

1.自定义单元格Cell类型:以定义一个DataGridViewDateTimePickerColumn为例(源码来自CodeProject)。

自定义DataGridViewDateTimePickerColumn
  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Text;
  5 using System.Windows.Forms;
  6 
  7 namespace NtControls
  8 {
  9    public class DataGridViewDateTimePickerColumn:DataGridViewColumn
 10     {
 11         public DataGridViewDateTimePickerColumn()
 12                 : base(new CalendarCell())
 13             {
 14             }
 15 
 16             public override DataGridViewCell CellTemplate
 17             {
 18                 get
 19                 {
 20                     return base.CellTemplate;
 21                 }
 22                 set
 23                 {
 24                     if (value != null &&
 25                         !value.GetType().IsAssignableFrom(typeof(CalendarCell)))
 26                     {
 27                         throw new InvalidCastException("Must be a CalendarCell");
 28                     }
 29                     base.CellTemplate = value;
 30                 }
 31             }
 32     }
 33     public class CalendarCell : DataGridViewTextBoxCell
 34     {
 35 
 36         public CalendarCell()
 37             : base()
 38         {
 39             // Use the short date format.
 40             this.Style.Format = "d";
 41         }
 42 
 43         public override void InitializeEditingControl(int rowIndex, object
 44             initialFormattedValue, DataGridViewCellStyle dataGridViewCellStyle)
 45         {
 46             // Set the value of the editing control to the current cell value.
 47             base.InitializeEditingControl(rowIndex, initialFormattedValue,
 48                 dataGridViewCellStyle);
 49             CalendarEditingControl ctl =
 50                 DataGridView.EditingControl as CalendarEditingControl;
 51 
 52             if (this.Value != System.DBNull.Value)
 53             {
 54                 ctl.Value = (DateTime)this.Value;
 55             }
 56 
 57         }
 58 
 59         public override Type EditType
 60         {
 61             get
 62             {
 63                 // Return the type of the editing contol that CalendarCell uses.
 64                 return typeof(CalendarEditingControl);
 65             }
 66         }
 67 
 68         public override Type ValueType
 69         {
 70             get
 71             {
 72                 // Return the type of the value that CalendarCell contains.
 73                 return typeof(DateTime);
 74             }
 75         }
 76 
 77         public override object DefaultNewRowValue
 78         {
 79             get
 80             {
 81                 // Use the current date and time as the default value.
 82                 return DateTime.Now;
 83             }
 84         }
 85     }
 86 
 87     class CalendarEditingControl : DateTimePicker, IDataGridViewEditingControl
 88     {
 89         DataGridView dataGridView;
 90         private bool valueChanged = false;
 91         int rowIndex;
 92 
 93         public CalendarEditingControl()
 94         {
 95             this.Format = DateTimePickerFormat.Short;
 96         }
 97 
 98         // Implements the IDataGridViewEditingControl.EditingControlFormattedValue 
 99         // property.
100         public object EditingControlFormattedValue
101         {
102             get
103             {
104                 return this.Value.ToShortDateString();
105             }
106             set
107             {
108                 if (value is String)
109                 {
110                     this.Value = DateTime.Parse((String)value);
111                 }
112             }
113         }
114 
115         // Implements the 
116         // IDataGridViewEditingControl.GetEditingControlFormattedValue method.
117         public object GetEditingControlFormattedValue(
118             DataGridViewDataErrorContexts context)
119         {
120             return EditingControlFormattedValue;
121         }
122 
123         // Implements the 
124         // IDataGridViewEditingControl.ApplyCellStyleToEditingControl method.
125         public void ApplyCellStyleToEditingControl(
126             DataGridViewCellStyle dataGridViewCellStyle)
127         {
128             this.Font = dataGridViewCellStyle.Font;
129             this.CalendarForeColor = dataGridViewCellStyle.ForeColor;
130             this.CalendarMonthBackground = dataGridViewCellStyle.BackColor;
131         }
132 
133         // Implements the IDataGridViewEditingControl.EditingControlRowIndex 
134         // property.
135         public int EditingControlRowIndex
136         {
137             get
138             {
139                 return rowIndex;
140             }
141             set
142             {
143                 rowIndex = value;
144             }
145         }
146 
147         // Implements the IDataGridViewEditingControl.EditingControlWantsInputKey 
148         // method.
149         public bool EditingControlWantsInputKey(
150             Keys key, bool dataGridViewWantsInputKey)
151         {
152             // Let the DateTimePicker handle the keys listed.
153             switch (key & Keys.KeyCode)
154             {
155                 case Keys.Left:
156                 case Keys.Up:
157                 case Keys.Down:
158                 case Keys.Right:
159                 case Keys.Home:
160                 case Keys.End:
161                 case Keys.PageDown:
162                 case Keys.PageUp:
163                     return true;
164                 default:
165                     return false;
166             }
167         }
168 
169         // Implements the IDataGridViewEditingControl.PrepareEditingControlForEdit 
170         // method.
171         public void PrepareEditingControlForEdit(bool selectAll)
172         {
173             // No preparation needs to be done.
174         }
175 
176         // Implements the IDataGridViewEditingControl
177         // .RepositionEditingControlOnValueChange property.
178         public bool RepositionEditingControlOnValueChange
179         {
180             get
181             {
182                 return false;
183             }
184         }
185 
186         // Implements the IDataGridViewEditingControl
187         // .EditingControlDataGridView property.
188         public DataGridView EditingControlDataGridView
189         {
190             get
191             {
192                 return dataGridView;
193             }
194             set
195             {
196                 dataGridView = value;
197             }
198         }
199 
200         // Implements the IDataGridViewEditingControl
201         // .EditingControlValueChanged property.
202         public bool EditingControlValueChanged
203         {
204             get
205             {
206                 return valueChanged;
207             }
208             set
209             {
210                 valueChanged = value;
211             }
212         }
213 
214         // Implements the IDataGridViewEditingControl
215         // .EditingPanelCursor property.
216         public Cursor EditingPanelCursor
217         {
218             get
219             {
220                 return base.Cursor;
221             }
222         }
223 
224         protected override void OnValueChanged(EventArgs eventargs)
225         {
226             // Notify the DataGridView that the contents of the cell
227             // have changed.
228             valueChanged = true;
229             this.EditingControlDataGridView.NotifyCurrentCellDirty(true);
230             base.OnValueChanged(eventargs);
231         }
232     }
233 }
调用的代码:
1 DataGridViewDateTimePickerColumn ColdatePicker = new DataGridViewDateTimePickerColumn(); 2 ColdatePicker.DataPropertyName = "gg";//绑定一个时间类型的数据字段 3 ColdatePicker.HeaderText = "时间"; 4 ColdatePicker.Name = "ColdatePicker";

DataGridVIew的使用学习_第1张图片

2.手工创建Column后绑定数据(不做介绍) 

3.让DataGridView奇数行和偶数行以不同的颜色显示

1 DataGridViewCellStyle dataGridViewCellStyle1 =new DataGridViewCellStyle();
2             dataGridViewCellStyle1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(255)))), ((int)(((byte)(255)))));
3             dataGridViewCellStyle1.ForeColor = System.Drawing.SystemColors.WindowText;
4             this.dataGridView1.AlternatingRowsDefaultCellStyle = dataGridViewCellStyle1;

DataGridVIew的使用学习_第2张图片

4.选择RowHeader,右击弹出菜单

 1  private void dgvRegionStatistic_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
 2         {
 3             if (e.Button==MouseButtons.Left)
 4             {
 5                 //dgvRegionStatistic.s(e.RowIndex);
 6             }
 7             else if (e.Button==MouseButtons.Right)
 8             {
 9                 dgvRegionStatistic.Rows[e.RowIndex].Selected = true;
10                 ContextMenuStrip munu = contextMenuStrip1;
11                 munu.Show(MousePosition.X, MousePosition.Y);
12             }
13         }

5.Drill表中字段StraId(int)依赖于Stra表中主键ID(int),查询Drill表显示地层信息为Stra表中的Stra_name字段。

View Code
 1  private DataTable GetTable(string sql)
 2         {
 3             string strConn = global::NcControls.Properties.Settings.Default.geoConnString;
 4             using (OleDbConnection sqlconn = new OleDbConnection(strConn))
 5             {
 6                 DataTable dt = new DataTable();
 7                 OleDbDataAdapter sqlda = new OleDbDataAdapter(sql, sqlconn);
 8                 sqlda.Fill(dt);
 9                 return dt;
10             }
11         }
12 
13         private void frmDrill_Load(object sender, EventArgs e)
14         {
15             dataGridView1.AutoGenerateColumns = false;
16             dataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.EnableResizing;
17             dataGridView1.ColumnHeadersHeight = 48;
18        dataGridView1.EditMode = DataGridViewEditMode.EditOnEnter;//鼠标点击一次就可以修改
19             dataGridView1.AllowUserToAddRows = false;
20            // dataGridView1.ReadOnly = true;
21 
22             System.Windows.Forms.DataGridViewTextBoxColumn Column1 = new DataGridViewTextBoxColumn();
23             Column1.DataPropertyName = "ID";
24             Column1.HeaderText = "编号";
25             Column1.Name = "Column1";
26             
27             System.Windows.Forms.DataGridViewTextBoxColumn ColLayerId = new DataGridViewTextBoxColumn();
28             ColLayerId.DataPropertyName = "Layer_id";
29             ColLayerId.HeaderText = "分层号";
30             ColLayerId.Name = "ColLayerId";
31 
32             System.Windows.Forms.DataGridViewTextBoxColumn ColHoleId = new DataGridViewTextBoxColumn();
33             ColHoleId.DataPropertyName = "HoleId";
34             ColHoleId.HeaderText = "钻孔号";
35             ColHoleId.Name = "ColHoleId";
36 
37             System.Windows.Forms.DataGridViewComboBoxColumn Column2 = new DataGridViewComboBoxColumn();
38             Column2.DisplayStyle = System.Windows.Forms.DataGridViewComboBoxDisplayStyle.Nothing;//和txtbox一样显示
39             Column2.Width = 160;
40             string sql1 = "select * from Stra;";           
41             Column2.DataPropertyName = "StraId";
42             Column2.DataSource = GetTable(sql1);
43             Column2.DisplayMember = "Stra_name";
44             Column2.ValueMember = "ID";
45 
46             DataGridViewActionButtonColumn colAction = new DataGridViewActionButtonColumn();
47             colAction.Name = "colAction";
48             colAction.Width = 160;
49 
50             this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
51             Column1,ColLayerId,ColHoleId,Column2,colAction});
52 
53             string sql2 = "select * from Drill";
54             this.dataGridView1.DataSource = GetTable(sql2);//在为ComboxCell添加完绑定后给DataGridView添加数据源
55 
56         }

DataGridVIew的使用学习_第3张图片

 参考文献

http://www.cnblogs.com/peterzb/archive/2009/05/29/1491891.html

http://msdn.microsoft.com/zh-cn/library/ms404353.aspx

http://msdn.microsoft.com/zh-cn/library/system.windows.forms.datagridview.autogeneratecolumns.aspx

 

你可能感兴趣的:(datagridview)