2013-08-19 63 views
1

基本上我想在編輯Datagridview中的某些列時顯示日曆。datagridview中的日曆列c#

繼MSDN的How to: Host Controls in Windows Forms DataGridView Cells之後,我可以在建築物中添加所需類型的列。

但在我的情況下,我必須使用由一個Excel閱讀器這給標題必須連接到日期類型列提供的數據源

private DataGridView AddCalendars(DataGridView dtgv) 
{ 
    dtgv.DataSource = controller.getEmptyDataTable();  // DataTable provided by excel reader 
    var l = dtgv.Columns.Count; 
    string[] dateColumns = {"date_received", "date_of_birth"}; 
    for (var i = 0; i < l; ++i) 
    { 
    if (dateColumns.Any(dtgv.Columns[i].HeaderText.Contains) 
    { 
     dtgv.Columns[i] = new CalendarColumn();  // this line does not work cause by readonly 
    } 
    } 
    return dtgv; 
} 

如何申請日曆列控制所選列?

或者,如何通過構建Datagridview的不同方式來獲得相同的結果?

回答

3

找到可接受的解決辦法解決此職位http://www.codeproject.com/Questions/175124/placing-datetimepicker-in-datagridview

private DateTimePicker cellDateTimePicker; 
private List<int> dateColumnsIndexes; 

public MainForm() 
{ 
    InitializeComponent(); 

    /// 
    this.cellDateTimePicker = new DateTimePicker(); 
    this.cellDateTimePicker.ValueChanged += new EventHandler(cellDateTimePickerValueChanged); 
    this.cellDateTimePicker.Visible = false; 
    this.cellDateTimePicker.CustomFormat = "dd/MM/yyyy"; 
    this.cellDateTimePicker.Format = DateTimePickerFormat.Custom; 
    this.dataGridView1.Controls.Add(cellDateTimePicker); 
    (...) 
} 

private void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e) 
{ 
    var index = masterDataGridView.CurrentCell.ColumnIndex; 
    if (this.dateColumnsIndexes.Contains(index)) 
    { 
    Rectangle tempRect = this.dataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, false);   
    cellDateTimePicker.Location = tempRect.Location; 
    cellDateTimePicker.Width = tempRect.Width; 
    try 
    { 
     cellDateTimePicker.Value = DateTime.Parse(dataGridView1.CurrentCell.Value.ToString()); 
    } 
    catch 
    { 
     cellDateTimePicker.Value = DateTime.Now; 
    } 
    cellDateTimePicker.Visible = true; 
    } 
} 

void cellDateTimePickerValueChanged(object sender, EventArgs e) 
{ 
    masterDataGridView.CurrentCell.Value = cellDateTimePicker.Value.ToString("dd/MM/yyyy"); 
    cellDateTimePicker.Visible = false; 
} 

private void AddCalendars(DataGridView dtgv) 
{ 
    dateColumnsIndexes = new List<int>(); 
    dtgv.DataSource = controller.getEmptyDataTable();  // DataTable provided by excel reader 
    var l = dtgv.Columns.Count; 
    string[] dateColumns = {"date_received", "date_of_birth"}; 
    for (var i = 0; i < l; ++i) 
    { 
    if (dateColumns.Any(dtgv.Columns[i].HeaderText.Contains) 
    { 
     dateColumnsIndexes.add(i); 
    } 
} 

}

工作