功能简介: 此方法可以自动生成隐藏列,日期列(DateTimePicker),Bool列(CheckBox),选择列(ComboBox),图片列。 //from:http://www.chinaaspx.com/comm/technet/Showtopic.aspx?Forum_ID=6&id=242050&Page=1
/// <summary> /// 日期列类 /// </summary> public class CalendarColumn : DataGridViewColumn { /// <summary> /// 构造 /// </summary> public CalendarColumn() : base(new CalendarCell()) { } /// <summary> /// 重写 /// </summary> public override DataGridViewCell CellTemplate { get { return base.CellTemplate; } set { // Ensure that the cell used for the template is a CalendarCell. if (value != null && !value.GetType().IsAssignableFrom(typeof(CalendarCell))) { throw new InvalidCastException("Must be a CalendarCell"); } base.CellTemplate = value; } } } /// <summary> /// 日期列值类 /// </summary> public class CalendarCell : DataGridViewTextBoxCell { /// <summary> /// 构造 /// </summary> public CalendarCell() : base() { // Use the short date format. this.Style.Format = "d"; } /// <summary> /// 重写 /// </summary> /// <param name="rowIndex"></param> /// <param name="initialFormattedValue"></param> /// <param name="dataGridViewCellStyle"></param> public override void InitializeEditingControl(int rowIndex, object initialFormattedValue, DataGridViewCellStyle dataGridViewCellStyle) { // Set the value of the editing control to the current cell value. base.InitializeEditingControl(rowIndex, initialFormattedValue, dataGridViewCellStyle); CalendarEditingControl ctl = DataGridView.EditingControl as CalendarEditingControl; ctl.Text = this.Value.ToString(); //ctl.Value = (DateTime)this.Value; } /// <summary> /// EditType /// </summary> public override Type EditType { get { // Return the type of the editing contol that CalendarCell uses. return typeof(CalendarEditingControl); } } /// <summary> /// ValueType /// </summary> public override Type ValueType { get { // Return the type of the value that CalendarCell contains. return typeof(DateTime); } } /// <summary> /// DefaultNewRowValue /// </summary> public override object DefaultNewRowValue { get { // Use the current date and time as the default value. return DateTime.Now; } } } /// <summary> /// 日期列编辑类 /// </summary> public class CalendarEditingControl : DateTimePicker, IDataGridViewEditingControl { DataGridView dataGridView; private bool valueChanged = false; int rowIndex; /// <summary> /// CalendarEditingControl /// </summary> public CalendarEditingControl() { this.Format = DateTimePickerFormat.Short; } // Implements the IDataGridViewEditingControl.EditingControlFormattedValue // property. /// <summary> /// EditingControlFormattedValue /// </summary> public object EditingControlFormattedValue { get { return this.Value.ToShortDateString(); } set { if (value is String) { this.Value = DateTime.Parse((String)value); } } } // Implements the // IDataGridViewEditingControl.GetEditingControlFormattedValue method. /// <summary> /// GetEditingControlFormattedValue /// </summary> /// <param name="context"></param> /// <returns></returns> public object GetEditingControlFormattedValue( DataGridViewDataErrorContexts context) { return EditingControlFormattedValue; } // Implements the // IDataGridViewEditingControl.ApplyCellStyleToEditingControl method. /// <summary> /// ApplyCellStyleToEditingControl /// </summary> /// <param name="dataGridViewCellStyle"></param> public void ApplyCellStyleToEditingControl( DataGridViewCellStyle dataGridViewCellStyle) { this.Font = dataGridViewCellStyle.Font; this.CalendarForeColor = dataGridViewCellStyle.ForeColor; this.CalendarMonthBackground = dataGridViewCellStyle.BackColor; } // Implements the IDataGridViewEditingControl.EditingControlRowIndex // property. /// <summary> /// EditingControlRowIndex /// </summary> public int EditingControlRowIndex { get { return rowIndex; } set { rowIndex = value; } } // Implements the IDataGridViewEditingControl.EditingControlWantsInputKey // method. /// <summary> /// EditingControlWantsInputKey /// </summary> /// <param name="key"></param> /// <param name="dataGridViewWantsInputKey"></param> /// <returns></returns> public bool EditingControlWantsInputKey( Keys key, bool dataGridViewWantsInputKey) { // Let the DateTimePicker handle the keys listed. switch (key & Keys.KeyCode) { case Keys.Left: case Keys.Up: case Keys.Down: case Keys.Right: case Keys.Home: case Keys.End: case Keys.PageDown: case Keys.PageUp: return true; default: return false; } } // Implements the IDataGridViewEditingControl.PrepareEditingControlForEdit // method. /// <summary> /// PrepareEditingControlForEdit /// </summary> /// <param name="selectAll"></param> public void PrepareEditingControlForEdit(bool selectAll) { // No preparation needs to be done. } // Implements the IDataGridViewEditingControl // .RepositionEditingControlOnValueChange property. /// <summary> /// RepositionEditingControlOnValueChange /// </summary> public bool RepositionEditingControlOnValueChange { get { return false; } } // Implements the IDataGridViewEditingControl // .EditingControlDataGridView property. /// <summary> /// EditingControlDataGridView /// </summary> public DataGridView EditingControlDataGridView { get { return dataGridView; } set { dataGridView = value; } } // Implements the IDataGridViewEditingControl // .EditingControlValueChanged property. /// <summary> /// EditingControlValueChanged /// </summary> public bool EditingControlValueChanged { get { return valueChanged; } set { valueChanged = value; } } // Implements the IDataGridViewEditingControl // .EditingPanelCursor property. /// <summary> /// EditingPanelCursor /// </summary> public Cursor EditingPanelCursor { get { return base.Cursor; } } /// <summary> /// OnValueChanged /// </summary> /// <param name="eventargs"></param> protected override void OnValueChanged(EventArgs eventargs) { // Notify the DataGridView that the contents of the cell // have changed. valueChanged = true; this.EditingControlDataGridView.NotifyCurrentCellDirty(true); base.OnValueChanged(eventargs); } } /// <summary> /// 刷新DataGridView /// </summary> /// <param name="dg">DataGridView名</param> /// <param name="sql">SQL语句</param> /// <param name="HideCols">隐藏列</param> /// <param name="DateCols">日期列</param> /// <param name="BoolCols">Bool列</param> /// <param name="ImageCols">图像列</param> /// <param name="ComboBoxCols">下拉列</param> /// <param name="Split">下拉列内容分隔符</param> public static void ReFlashGrid(DataGridView dg, string sql, string HideCols, string DateCols, string BoolCols,string ImageCols, string ComboBoxCols,char Split) { try { dg.Rows.Clear(); dg.Columns.Clear(); DataSet ds = new DataSet(); ds = DBbind(sql); dg.AutoGenerateColumns = true; //dg.ColumnHeadersBorderStyle = //DataGridViewHeaderBorderStyle.Single; //dg.CellBorderStyle = DataGridViewCellBorderStyle.Single; //dg.RowHeadersVisible = false; dg.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None; dg.EditMode = DataGridViewEditMode.EditOnEnter; //dg.DataMember = ds.Tables[0].TableName; dg.AutoResizeRowHeadersWidth( DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders); dg.Sorted += new EventHandler(dg_Sorted); dg.DataError+=new DataGridViewDataErrorEventHandler(dg_DataError); dg.ShowCellErrors = false; dg.MultiSelect = false; string[] tmpHide = HideCols.Split(','); string[] tmpDate = DateCols.Split(','); string[] tmpBool = BoolCols.Split(','); string[] tmpCombo = ComboBoxCols.Split(','); string[] tmpImage = ImageCols.Split(','); for (int i = 0; i < ds.Tables[0].Columns.Count; i++) { for (int j = 0; j < tmpDate.Length; j++) { if (ds.Tables[0].Columns[i].Caption.ToLower().Trim() == tmpDate[j].ToLower().Trim()) { dg.Columns.Add(new CalendarColumn()); dg.Columns[i].Name = ds.Tables[0].Columns[i].Caption; dg.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.None; break; } } if (dg.Columns.Count == i + 1) continue; for (int j = 0; j < tmpImage.Length; j++) { if (ds.Tables[0].Columns[i].Caption.ToLower().Trim() == tmpImage[j].ToLower().Trim()) { dg.Columns.Add(new DataGridViewImageColumn()); dg.Columns[i].Name = ds.Tables[0].Columns[i].Caption; dg.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.None; break; } } if (dg.Columns.Count == i + 1) continue; for (int j = 0; j < tmpBool.Length; j++) { if (ds.Tables[0].Columns[i].Caption.ToLower().Trim() == tmpBool[j].ToLower().Trim()) { dg.Columns.Add(new DataGridViewCheckBoxColumn()); dg.Columns[i].Name = ds.Tables[0].Columns[i].Caption; dg.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.None; break; } } if (dg.Columns.Count == i + 1) continue; for (int j = 0; j < tmpCombo.Length; j++) { if (ds.Tables[0].Columns[i].Caption.ToLower().Trim() == tmpCombo[j].ToLower().Trim()) { dg.Columns.Add(new DataGridViewComboBoxColumn()); dg.Columns[i].Name = ds.Tables[0].Columns[i].Caption; dg.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.None; break; } } if (dg.Columns.Count == i + 1) { continue; } else { dg.Columns.Add(ds.Tables[0].Columns[i].Caption, ds.Tables[0].Columns[i].Caption); } } for (int i = 0; i < dg.Columns.Count; i++) { for (int j = 0; j < tmpHide.Length; j++) { if (dg.Columns[i].Name.ToLower().Trim() == tmpHide[j].ToLower().Trim()) { dg.Columns[i].Visible = false; } } } for (int i = 0; i < ds.Tables[0].Rows.Count; i++) { dg.Rows.Add(); dg.Rows[i].HeaderCell.Value = Convert.ToString(i + 1); for (int j = 0; j < dg.Columns.Count; j++) { bool iscombo = false; for (int k = 0; k < tmpCombo.Length; k++) { if (dg.Columns[j].Name.ToLower().Trim() == tmpCombo[k].ToLower().Trim()) { object[] tmpargs = ds.Tables[0].Rows[i][j].ToString().Split(Split); DataGridViewComboBoxCell aa = new DataGridViewComboBoxCell(); aa.DataSource = tmpargs; dg[j, i] = aa; if (tmpargs.Length >= 1) { dg[j, i].Value = tmpargs[0]; } iscombo = true; break; } if (iscombo == false) { if (dg.Columns[j].CellType.Name == "DataGridViewTextBoxCell") { dg[j, i].Value = ds.Tables[0].Rows[i][j].ToString(); } else { dg[j, i].Value = ds.Tables[0].Rows[i][j]; } } } } } } catch (Exception eee) { MessageBox.Show(eee.Message); } } static void dg_Sorted(object sender, EventArgs e) { try { for (int i = 0; i < ((DataGridView)sender).Rows.Count;i++ ) { ((DataGridView)sender).Rows[i].HeaderCell.Value = Convert.ToString(i + 1); } } catch {} } static void dg_DataError(object sender, DataGridViewDataErrorEventArgs e) { return; } 调用方法: Class.ReFlashGrid(this.dataGridView1, "select * from JC_家床建撤床","id,uid,jid","建床日期","","","",','); 注: Class.ReFlashGrid()方法里的DataSet自己写数据库连接自行填充