C#:DataGridView中列类型使用时间控件和下拉列表的自动匹配
来源:http://blog.csdn.net/kingzone_2008/article/details/8470666
1. DataGridView中使用时间控件作为列类型 DataGridView中默认不提供DateTimePicker类型的列类型,因此可以通过控件的覆盖模拟所需的功能。详细步骤如下: 第一步,将DataGridView单元格设置为DataGridViewTextBoxColumn类型(文本单元格); 第二步,创建一个DateTimePicker控件dateTimePicker1(时间控件),Visible属性设置为false; 第三步,将时间控件的坐标设置为对应文本单元格的坐标; 第四步,若文本单元格原来为空,则时间控件设置为当前时间,若有值,则时间控件Value属性设置为其值; 第五步,dateTimePicker1的ValueChanged事件和Leave事件的处理。 下面是第三步和第四步的代码: private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e) { // 设置坐标 this.dateTimePicker1.Left = this.dataGridView1.Left + this.dataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, false).X; this.dateTimePicker1.Top = this.dataGridView1.Top + this.dataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, false).Y; // 值 if (this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value == null || this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString() == "") { this.dateTimePicker1.Value = DateTime.Now; this.dateTimePicker1.Visible = true; } else { this.dateTimePicker1.Value = Convert.ToDateTime(this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value); this.dateTimePicker1.Visible = true; } }
第五步的代码:
private void dateTimePicker1_Leave(object sender, EventArgs e) { this.dateTimePicker1.Visible = false; //this.dataGridView1.CurrentCell.Value = this.dateTimePicker1.Value; } private void dateTimePicker1_ValueChanged(object sender, EventArgs e) { //this.dateTimePicker1.Visible = false; this.dataGridView1.CurrentCell.Value = this.dateTimePicker1.Value; }
2. DataGridView中实现DataGridViewComboBoxColumn的自动匹配
这里假定已经设置了DataGridViewComboBoxColumn列的DataSource,则只需在dataGridView的EditingControlShowing事件中添加相关处理逻辑。
// 显示用于编辑单元格的控件时触发 private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) { if (e.Control.GetType() == typeof(DataGridViewComboBoxEditingControl)) { //((ComboBox)e.Control).DropDownStyle = ComboBoxStyle.DropDown; ComboBox cbo = e.Control as ComboBox; cbo.DropDownStyle = ComboBoxStyle.DropDown; cbo.AutoCompleteMode = AutoCompleteMode.SuggestAppend; // 可能导致绑定多个监听函数,重复执行 //cbo.SelectedValueChanged += new EventHandler(cbo_SelectedValueChanged); //Console.WriteLine(cbo.SelectedText); } } void cbo_SelectedValueChanged(object sender, EventArgs e) { // TODO }
3. DataGridView自动滚动到最新的记录
代码如下:
// 滚动条滚动到最后 if (this.dataGridView1.Rows.Count >= 1) { this.dataGridView1.FirstDisplayedScrollingRowIndex = this.dataGridView1.Rows.Count - 1; }