Цитата(-ser- @ 7.6.2006, 07:51 ) | Цитата(kulibin @ 26.5.2006, 10:38 ) Сделал чтобы чекбокс отображался в дейттаймпикере.
вот тут ты асс. я даже не представляю как это. да и стоит ли смешивать одно с другим.
Цитата(kulibin @ 26.5.2006, 10:38 ) И ещё чекед чёто не пойму как привязать к конкретной ячейке
перевожу для себя вопрос: как связать чекбокс с ячейкой. |
на самом деле всё гораздо проще - в стандартном дейттаймпикере есть свойства showcheckbox и checked . Т.е. это стандартный функционал обычного дейттаймпикера - токо и всего . А мне нужно только им воспользоваться для того, чтобы если у меня имеется столбец с датой и он позволяет dbnull.value - чтобы дату туда можно было не только поставить - но и убрать. Ну тоисть со стандартным мс-ным примером CalendarColumn который этого не поддерживает получается такая петрушка: дату с помощью этого дейттаймпикера поставить можно - а вот убрать фигушки. А если например у меня суперпрограмма с заказами и там есть дата заказа - обязательная - и даты отгрузки и оплаты. Понятно что даты отгрузки и оплаты должны иметь возможность быть пустыми. Вот для этого мне и нужно свойство showcheckbox в дейттаймпикере увязать с AlowDbNull а cheked с dbnull.value. Вот такие пироги.
Теперь отчёт о проделаной работе . Отображать - скрывать чекбокс в зависимости от значения свойства столбца alowdbnull получилось - уря!!! Токо есть один побочный эффект: оно в основном работает нормально - но иногда происходит странный глюк и при снятии галочки с чекбокса значение даты из ячейки датагридвью не убирается . пол ночи просидел в попытках разобраться где жук этот сидит. Ничё не понял . Вот код. Не думаю что кто-то разберётся в нём раньше меня - но если вдруг так случится - то буду очень рад 
Код | using System; using System.Windows.Forms; using System.Data;
namespace GTools { public class CalendarColumn : DataGridViewColumn { public CalendarColumn() : base(new CalendarCell()) { }
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; } } }
public class CalendarCell : DataGridViewTextBoxCell {
public CalendarCell() : base() { // Use the short date format. this.Style.Format = "d"; }
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; bool nlb = false; try { if (this.DataGridView.DataSource is DataView) { nlb = ((DataView)this.DataGridView.DataSource).Table.Columns[this.OwningColumn.Name].AllowDBNull; } else if (this.DataGridView.DataSource is BindingSource) { nlb = ((DataView)((BindingSource)this.DataGridView.DataSource).DataSource).Table.Columns[this.OwningColumn.Name].AllowDBNull; } else // datatable. если нет - то выдаём ошибку. { nlb = ((DataTable)this.DataGridView.DataSource).Columns[this.OwningColumn.Name].AllowDBNull; } } catch (Exception ex) { throw new Exception("такой datasource для datagridview не поддерживается классом calendarcolumn.", ex); } ctl.ShowCheckBox = nlb; try { ctl.Value = (DateTime)this.Value; } catch (Exception ex) { ctl.Value = DateTime.Now; ctl.Checked = false; } }
public override Type EditType { get { // Return the type of the editing contol that CalendarCell uses. return typeof(CalendarEditingControl); } }
public override Type ValueType { get { // Return the type of the value that CalendarCell contains. return typeof(DateTime); } }
public override object DefaultNewRowValue { get { // Use the current date and time as the default value. return null; } } }
class CalendarEditingControl : DateTimePicker, IDataGridViewEditingControl { DataGridView dataGridView; private bool valueChanged = false; int rowIndex;
public CalendarEditingControl() { this.Format = DateTimePickerFormat.Short;
}
// Implements the IDataGridViewEditingControl.EditingControlFormattedValue // property. public object EditingControlFormattedValue { get { if (this.Checked) { return this.Value.ToShortDateString(); } else { return string.Empty; } } set { String newValue = value as String; if (newValue != null && newValue != string.Empty) { this.Value = DateTime.Parse(newValue); if (this.ShowCheckBox) { this.Checked = true; } } else if (this.ShowCheckBox) { this.Checked = false; } else { this.Value = DateTime.Now; } } }
// Implements the // IDataGridViewEditingControl.GetEditingControlFormattedValue method. public object GetEditingControlFormattedValue( DataGridViewDataErrorContexts context) { return EditingControlFormattedValue; }
// Implements the // IDataGridViewEditingControl.ApplyCellStyleToEditingControl method. public void ApplyCellStyleToEditingControl( DataGridViewCellStyle dataGridViewCellStyle) { this.Font = dataGridViewCellStyle.Font; this.CalendarForeColor = dataGridViewCellStyle.ForeColor; this.CalendarMonthBackground = dataGridViewCellStyle.BackColor; }
// Implements the IDataGridViewEditingControl.EditingControlRowIndex // property. public int EditingControlRowIndex { get { return rowIndex; } set { rowIndex = value; } }
// Implements the IDataGridViewEditingControl.EditingControlWantsInputKey // method. 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. public void PrepareEditingControlForEdit(bool selectAll) { // No preparation needs to be done. }
// Implements the IDataGridViewEditingControl // .RepositionEditingControlOnValueChange property. public bool RepositionEditingControlOnValueChange { get { return false; } }
// Implements the IDataGridViewEditingControl // .EditingControlDataGridView property. public DataGridView EditingControlDataGridView { get { return dataGridView; } set { dataGridView = value; } }
// Implements the IDataGridViewEditingControl // .EditingControlValueChanged property. public bool EditingControlValueChanged { get { return valueChanged; } set { valueChanged = value; } }
// Implements the IDataGridViewEditingControl // .EditingPanelCursor property. public Cursor EditingPanelCursor { get { return base.Cursor; } }
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); } } }
|
Добавлено @ 10:11 вот ключевой момент:
Код | 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; bool nlb = false; try { if (this.DataGridView.DataSource is DataView) { nlb = ((DataView)this.DataGridView.DataSource).Table.Columns[this.OwningColumn.Name].AllowDBNull; } else if (this.DataGridView.DataSource is BindingSource) { nlb = ((DataView)((BindingSource)this.DataGridView.DataSource).DataSource).Table.Columns[this.OwningColumn.Name].AllowDBNull; } else // datatable. если нет - то выдаём ошибку. { nlb = ((DataTable)this.DataGridView.DataSource).Columns[this.OwningColumn.Name].AllowDBNull; } } catch (Exception ex) { throw new Exception("такой datasource для datagridview не поддерживается классом calendarcolumn.", ex); } ctl.ShowCheckBox = nlb; try { ctl.Value = (DateTime)this.Value; } catch (Exception ex) { ctl.Value = DateTime.Now; ctl.Checked = false; } }
|
и вот:
Код | // Implements the IDataGridViewEditingControl.EditingControlFormattedValue // property. public object EditingControlFormattedValue { get { if (this.Checked) { return this.Value.ToShortDateString(); } else { return string.Empty; } } set { String newValue = value as String; if (newValue != null && newValue != string.Empty) { this.Value = DateTime.Parse(newValue); if (this.ShowCheckBox) { this.Checked = true; } } else if (this.ShowCheckBox) { this.Checked = false; } else { this.Value = DateTime.Now; } } }
|
Я по последнему куску этому никак не пойму момента одного: set вообще не работает никогда - на нём точка останова стоит хронически и не разу не сработала. Странно как-то. А get активно используется - и вроде честно работает. |