//自己学习,参考多篇文章,未能写入文章来源敬请原谅!
// 采用单元格事件响应,datagridview 中没有textchange响应事件
/*
有几点要说明的
1. EditingControlShowing 是DataGridView自带的事件,当某个cell被编辑时就会激发该事件。接着就到了dataGridView1_EditingControlShowing 函数,然后(if…else if…)判断那个cell是DataGridViewComboBoxEditingControl还是DataGridViewTextBoxEditingControl 控件类型。判断好控件类型之后就可以用该类型自带的事件,例如DataGridViewComboBoxEditingControl 自带的SelectedIndexChanged 事件。
2. 为什么用dataGridView1.CurrentCell.EditedFormattedValue而不是dataGridView1.CurrentCell.Value,因为处于编辑状态的cell的Value是没有同时更新的,我们更改的是它的EditedFormattedValue。这个区别当然有好处,这里不谈。
3. 为什么要加一句e.CellStyle.BackColor = Color.FromName("window") ?实践是检验真理的标准,不妨去掉这句运行一下就清楚了。
*/
public partial class Arrange : Form { public Arrange() { InitializeComponent(); this.dataGridView1.EditingControlShowing += new DataGridViewEditingControlShowingEventHandler(dataGridView1_EditingControlShowing); } //编辑cell时激发的事件 void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) { if (e.Control.GetType().Equals(typeof(DataGridViewTextBoxEditingControl)))//cell为类TextBox时 { e.CellStyle.BackColor = Color.FromName("window"); DataGridViewTextBoxEditingControl editingControl = e.Control as DataGridViewTextBoxEditingControl; editingControl.TextChanged += new EventHandler(editingControl_TextChanged); } } //TextBox的TextChanged事件 void editingControl_TextChanged(object sender, EventArgs e) { if (sender is DataGridViewTextBoxEditingControl && dataGridView1.CurrentCell != null && dataGridView1.Columns[dataGridView1.CurrentCell.ColumnIndex].Name == "Column2") { int cursorPos = ((DataGridViewTextBoxEditingControl)sender).SelectionStart; string oldText = ((DataGridViewTextBoxEditingControl)sender).Text; StringBuilder newText = new StringBuilder(); int numCount = 0; bool isColon = false; for (int i = 0; i < oldText.Length; i++) { System.Text.RegularExpressions.Match match = System.Text.RegularExpressions.Regex.Match(oldText[i].ToString(), "[0-9]"); if (match.Success) { numCount++; if (numCount == 3 && isColon == false) { newText.Append(":"); isColon = true; cursorPos++; // 位置調整 } newText.Append(oldText[i]); } else { if (":".Equals(oldText[i].ToString()) && isColon == false && (numCount == 1 || numCount == 2)) { newText.Append(":"); isColon = true; } } } if (!(oldText.Equals(newText.ToString()))) { ((DataGridViewTextBoxEditingControl)sender).Text = newText.ToString(); ((DataGridViewTextBoxEditingControl)sender).SelectionLength = 0; if (cursorPos > newText.ToString().Length) { ((DataGridViewTextBoxEditingControl)sender).SelectionStart = newText.ToString().Length; } else { ((DataGridViewTextBoxEditingControl)sender).SelectionStart = cursorPos; } } } } }