今天做項目時遇到這個問題,隨從網上找例子,找了半天終於從csdn上面找了一個比較合適的,現在公布出來,供大家參考(只是選擇日期的-_-)
1、先聲明DateTimePicker 對象(公共的)
private DateTimePicker dTimePicker = new DateTimePicker();
2、在Form_Load()裡邊加入以下代碼:
dTimePicker.Visible = false; //默認不顯示
dTimePicker.Format = DateTimePickerFormat.Custom;//DateTimePicker 的格式為自定義dTimePicker.CustomFormat = "yyyy-MM-dd HH:mm:ss";//DateTimePicker 的自定義類型
dTimePicker.TextChanged += new EventHandler( dTimePicker_TextChanged );//當DateTimePicker 文本變化時賦值操作
private void dTimePicker_TextChanged( object sender, EventArgs e )
{
//把dTimePicker的Text值賦給dataGridView1選中的單元格值
dgvFKDB.CurrentCell.Value = dTimePicker.Text;
}
private void dgvFKDB_CurrentCellChanged( object sender, EventArgs e )
{
DataGridViewCell CurrnetCell = this.dgvFKDB.CurrentCell;
if (CurrnetCell != null && CurrnetCell.OwningColumn.Name == "FKSJ")
{
//獲得dataGridView1選中單元格顯示區域的矩形
Rectangle Rect = this.dgvFKDB.GetCellDisplayRectangle( CurrnetCell.ColumnIndex, CurrnetCell.RowIndex, true );
//顯示dTimePicker在dataGridView1選中單元格顯示區域的矩形裡面,即選中單元格內
dTimePicker.Visible = true;
dTimePicker.Top = Rect.Top;
dTimePicker.Left = Rect.Left;
dTimePicker.Height = Rect.Height;
dTimePicker.Width = Rect.Width;
//dTimePicker控件獲取初始值為dataGridView1選中單元格值
dTimePicker.Text = dgvFKDB.Rows[CurrnetCell.RowIndex].Cells[CurrnetCell.ColumnIndex].Value.ToString();
}
else
{
this.dTimePicker.Visible = false;
}
}
本例子由csdn上面改編而來。
源碼下載http://www.BkJia.com/uploadfile/2012/0321/20120321083518126.rar(csdn上面的,可參考)