来自:http://www.cnblogs.com/ojekleen/articles/dataGridView.html
public Form1()
{
InitializeComponent();
}
//定义一个DateTimePicker控件
private DateTimePicker dTimePicker = new DateTimePicker();
//定义一个DataSet
private DataSet ds;
private void Form1_Load(object sender, EventArgs e)
{
//隐藏dTimePicker
dTimePicker.Visible = false;
//dataGirdView1控件数据绑定
Data_Bind();
//定义控件dTimePicker当Text变更时委托于事件dTimePicker_TextChanged
dTimePicker.TextChanged += new EventHandler(dTimePicker_TextChanged);
//dataGridView1添加控件dTimePicker
dataGridView1.Controls.Add(dTimePicker);
}
/**//// <summary>
/// dataGirdView绑定数据
/// </summary>
private void Data_Bind()
{
string sqlstr = "select businessname,lastlogindate from business";
ds = SqlHelper.ExecuteDS(CommandType.Text, sqlstr);
dataGridView1.DataSource = ds.Tables[0].DefaultView;
}
//事件dTimePicker_TextChanged,当dTimePicker当Text变更时触发
private void dTimePicker_TextChanged(object sender, EventArgs e)
{
//把dTimePicker的Text值赋给dataGridView1选中的单元格值
dataGridView1.CurrentCell.Value = dTimePicker.Text;
}
private void dataGridView1_Scroll(object sender, ScrollEventArgs e)
{
//当dataGridView1滚动条移动时dTimePicker控件隐藏
dTimePicker.Visible = false;
}
private void dataGridView1_ColumnWidthChanged(object sender, DataGridViewColumnEventArgs e)
{
//当dataGridView1的列宽改变时dTimePicker控件隐藏
dTimePicker.Visible = false;
}
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
//判断选中行时日期类型
//dt = ds.Tables[0];
Type t = ds.Tables[0].Columns[dataGridView1.CurrentCell.ColumnIndex].DataType;
DateTime d = DateTime.Now;
if (t== d.GetType() )
{
//获得dataGridView1选中单元格显示区域的矩形
Rectangle Rect = this.dataGridView1.GetCellDisplayRectangle(this.dataGridView1.CurrentCell.ColumnIndex, this.dataGridView1.CurrentCell.RowIndex, false);
//显示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=dataGridView1.CurrentCell.Value.ToString();
}
}