一个项目中要实现DataGrid的编辑功能我的代码如下:
- #region DataGrid编辑
- private DataGridCell editCell;
- private bool inEditMode = false;
- private bool inUpdateMode = false;
- private void dataGrid1_CurrentCellChanged(object sender, EventArgs e)
- {
- if (!inUpdateMode)
- {
- if (inEditMode && !dataGrid1.CurrentCell.Equals(editCell))
- {
- ExitEditedMode(true);
- }
- // Enter edit mode
- editCell = dataGrid1.CurrentCell;
- if (dataGrid1.CurrentCell.ColumnNumber != 2 && dataGrid1.CurrentCell.ColumnNumber!=3)
- return;
- txtEdit.Text = ((double)dataGrid1[editCell.RowNumber, editCell.ColumnNumber]).ToString();
- Rectangle cellPos = dataGrid1.GetCellBounds(editCell.RowNumber,
- editCell.ColumnNumber);
- txtEdit.Left = cellPos.Left + 8;
- txtEdit.Top = cellPos.Top + dataGrid1.Top - 1;
- txtEdit.Width = cellPos.Width + 2;
- txtEdit.Height = cellPos.Height;
- txtEdit.Visible = true;
- inEditMode = true;
- txtEdit.Focus();
- txtEdit.SelectionStart = txtEdit.Text.Length;
- }
- }
- // Update or Cancel edited cell
- private void ExitEditedMode(bool isUpdate)
- {
- inUpdateMode = true;
- //dataGrid1.Visible = false;
- DataGridCell currentCell = dataGrid1.CurrentCell;
- if (isUpdate)
- dataGrid1[editCell.RowNumber, editCell.ColumnNumber] = txtEdit.Text;
- dataGrid1.CurrentCell = currentCell;
- //dataGrid1.Visible = true;
- inUpdateMode = false;
- txtEdit.Visible = false;
- inEditMode = false;
- }
- private void dataGrid1_MouseUp(object sender, MouseEventArgs e)
- {
- DataGrid.HitTestInfo hitTest = dataGrid1.HitTest(e.X, e.Y);
- if (hitTest.Type == DataGrid.HitTestType.ColumnHeader)
- {
- // Exit edit mode
- txtEdit.Visible = false;
- inEditMode = false;
- // Sort tapped column
- DataTable dataTable = (DataTable)dataGrid1.DataSource;
- DataView dataView = dataTable.DefaultView;
- string columnName = dataTable.Columns[hitTest.Column].ColumnName;
- if (dataView.Sort == columnName)
- dataView.Sort = columnName + " DESC";
- else
- dataView.Sort = columnName;
- }
- }
- private void txtEdit_KeyDown(object sender, KeyEventArgs e)
- {
- if (e.KeyCode == Keys.Escape)
- {
- ExitEditedMode(false);
- }
- else if (e.KeyCode == Keys.Enter)
- {
- ExitEditedMode(true);
- }
- }
- #endregion
- private void txtEdit_LostFocus(object sender, EventArgs e)
- {
- ExitEditedMode(true);
- }
原文地址是:[url=http://www.cnblogs.com/dagon007/archive/2005/05/24/161202.html][/url]
这个可以实现此功能,但是当移动滚动条时文本框不会消失,这样,会跟着滚动条跑,
我开始以为可以在文本框的焦点丢失事件中处理,可是移动滚动条时根本不会触发焦点丢失事件,
我现在有一个想法就是通过DataGrid的鼠标事件来判断 是否是在拖动滚动条,但是不知道要怎么写?
求Ce版的高手帮忙看看,
或者有别的思路说说也行